This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Function pointer casts and warnings
- To: gcc at gcc dot gnu dot org
- Subject: Function pointer casts and warnings
- From: Dalibor Topic <topic at mpi-sb dot mpg dot de>
- Date: Fri, 30 Jun 2000 16:52:31 +0200 (MET DST)
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, will crash on most systems. The test
function believes to call a function that requires no arguments on its
stack, while the called function in fact expects one argument to be on
stack.
It pops its argument off the stack, interprets it as a pointer to
an int, and changes that int's value. Since the argument is not an int
pointer in the first place ... boom!
I don't know if there is an appropriate warning in gcc, I didn't find any.
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.
What do you think?
Dalibor Topic