This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Function pointer casts and warnings
- To: Andreas Schwab <schwab at suse dot de>
- Subject: Re: Function pointer casts and warnings
- From: Dalibor Topic <topic at mpi-sb dot mpg dot de>
- Date: Mon, 3 Jul 2000 14:43:13 +0200 (MET DST)
- cc: gcc at gcc dot gnu dot org
Hello Andreas,
On Mon, 3 Jul 2000, Andreas Schwab wrote:
> Dalibor Topic <topic@mpi-sb.mpg.de> writes:
>
> |> This program, although it's legal C
>
> No, it's not. It's invoking undefined behaviour.
I should have said "it complies to syntax rules of C" instead of
"legal" to clarify my point. You can compile it and get a program you can
run. When you run it, the behaviour is undefined.
> |> 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.
When you do something like
((void (*) (void)) f) ();
you also get undefined behaviour if f is declared as in
void f (int* a);
While casting function pointer types around is always safe, using cast
function pointers is not always safe. A compiler should know the type of
f at compile time, and it should be able to recognize the cast to a
different type (void (*) (void)) at compile time. Then the compiler should
detect that the cast function is called.
Knowing that a function of some type is invoked with a wrong type, the
compiler could generate a warning.
In my first post, I had the example of a callback function test. The
compiler could detect that the function pointer f is cast to another
function pointer type before it is passed to the test function. It could
compare the cast type with the original type and detect that the
original function type expects a different set of arguments.
Invoking the function f in the test function through the cast type leads,
as you have pointed out, to undefined behaviour. Given what the compiler
should know about the types of involved functions, I think it could
generate a warning saying "do you really mean to do this?" :)
read ya,
Dalibor Topic