Why NULL is 0 (actually, why NULL is inadequate)
Ray Butterworth
rbutterworth at watmath.waterloo.edu
Wed Apr 6 03:36:53 AEST 1988
About the best way I've seen of convincing people of why you
can't simply use 0, or NULL, or 0L, or (void*)0, or any such
single token as a null pointer is to consider the following
function call:
auto char *bigstring;
bigstring = concatenate("This", " ", "is", " ", "it", ".", (char*)0);
where concatenate() mallocs enough memory, copies all its arguments
into one long string, and returns a pointer to that string.
It takes a variable number of arguments of which the last must be
a null (char *) pointer.
Now on any compiler for which a null character pointer is different
from the int 0, whether with a different size or a non-zero bit pattern,
there is absolutely no way that the compiler can automatically generate
a correct value for the last argument. Even prototypes won't help
in this case.
You may use (char*)0, NULL_P(char*), (char*)NULL, or whatever
your favourite is. But you must explicitly put the (char*) type
in there somehow or other.
If you simply use 0, NULL, 0L, or something that doesn't mention
(char*), it might just happen to work on YOUR compiler NOW, but
there is no reason you should assume that this code will work
anywhere else at any other time. It is simply wrong.
And before someone suggests defining NULL as (char*)0, remember
that there are machines for which sizeof(char*) is not the same
as sizeof(long*). All that does is give you something else that
is wrong but happens to work in a few more circumstances. It is
still wrong.
More information about the Comp.lang.c
mailing list