This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Function pointer casts and warnings
- To: Dalibor Topic <topic at mpi-sb dot mpg dot de>
- Subject: Re: Function pointer casts and warnings
- From: Andreas Schwab <schwab at suse dot de>
- Date: Mon, 3 Jul 2000 11:32:41 +0200
- Cc: gcc at gcc dot gnu dot org
- References: <Pine.GSO.4.10.10006301559160.10847-100000@orion>
Dalibor Topic <topic@mpi-sb.mpg.de> writes:
|> Hi,
|>
|> I browsed through the mailing list archives and the docs, but I couldn't
|> find anything about suspicious function pointer casts. Let's say you have
|>
|> /* a function returning nothing and accepting a pointer to an int */
|> void f (int* a) {
|> /* write some weird value into the integer */
|> *a = *a * *a;
|> }
|>
|> /* a function accepting a function pointer to a function returning
|> and accepting nothing
|> */
|> void test (void (* func) (void)) {
|> func();
|> }
|>
|> int main (void) {
|> /* legal C, but ... very dangerous! */
|> test ((void (*) (void)) f);
|>
|> return 0;
|> }
|>
|> This program, although it's legal C
No, it's not. It's invoking undefined behaviour.
|> I don't know if there is an appropriate warning in gcc, I didn't find
|> any.
You are using a cast, so gcc believes you know what you are doing. Since
you don't, you can expect undefined behaviour.
|> gcc 2.95.2 -Wall on Solaris compiled the file without complaint. I'd find
|> a warning about suspicious function pointer casts quite nice, since it
|> would let you automatically take care of such bugs.
The cast by itself is not suspicious in any way (you can always cast
between any two function pointers without losing information), but you
fail to cast the pointer back to the right type. There is nothing a
compiler can do to warn you.
Andreas.
--
Andreas Schwab "And now for something
SuSE Labs completely different."
Andreas.Schwab@suse.de
SuSE GmbH, Schanzäckerstr. 10, D-90443 Nürnberg