gcc and NULL function pointers.

Peter Holzer hp at vmars.tuwien.ac.at
Mon Jun 10 22:57:40 AEST 1991


sef at kithrup.COM (Sean Eric Fagan) writes:


>ANSI does not require a prototype for non-variardic functions (as far as I
>can tell).  As a result, for a certain class of popular machines, under
>certain compiler options, defining NULL as 0 will be incorrect, while
>'(void*)0' is correct.

>And the program that would core-dump on this would be perfectly correct,
>according to ANSI.  The header file would, therefore, be wrong.

No.

Consider the following program on a machine where the representation of
char/void * and int * is different:

-----------------------------------------------------------------------
#define NULL	((void *)0)
int printf (char const * fmt, ...);

int main ()
{
	a (NULL);
	return 0;
}

int a (ip)
	int * ip;
{
	if (ip != NULL) printf ("%d\n", * ip);
}
-----------------------------------------------------------------------
The function expects a pointer to int, but gets a pointer-to-void. Thus
the contents of ip are undefined and it may well compare != NULL,
causing a core dump (or crash, or rude mail to your boss :-) on the
printf.

Moral: If no prototypes are in scope you always have to cast NULL to
the correct pointer type. So it does not matter if NULL is defined as 0
or (void *)0. Of course (void *)0 may save many sloppy programmers, but
it can cause problems if you want to cast NULL to a function pointer
(as the original poster mentioned).

--
|    _  | Peter J. Holzer                       | Think of it   |
| |_|_) | Technical University Vienna           | as evolution  |
| | |   | Dept. for Real-Time Systems           | in action!    |
| __/   | hp at vmars.tuwien.ac.at                 |     Tony Rand |



More information about the Comp.std.c mailing list