Subject: Re: NULL return value checking
To: None <firstname.lastname@example.org>
From: der Mouse <mouse@Rodents.Montreal.QC.CA>
Date: 04/24/2002 11:20:40
Two things here. First, TLD writes
> I read somewhere, NULL can be != 0
> IMHO assuming NULL == 0 is bad practice if portability is a target.
Others have said similar things.
There are two ways in which it makes sense to say "NULL == 0": one is
"null pointer is all-bits-zero", the other is "null pointer compares
equal to zero in the language". [%]
The former is not guaranteed by the language, but the latter is. I
suspect this may be the source of some of the confusion in this thread.
[%] Actually, there's a third, "NULL is #defined as 0" (as opposed to,
say, (void *)0), but that's not interesting at the moment.
Also, Patrick Welche writes
> You mentioned needing to cast NULL, but in the style guide it says
> * Casts and sizeof's are not followed by a space. NULL is any
> * pointer type, and doesn't need to be cast, so use NULL instead
> * of (struct foo *)0 or (struct foo *)NULL. Also, test pointers
> * against NULL. I.e. use:
> so, did you mean, just cast in function arguments, or all the time?
In function arguments, and then only when there is no prototype in
scope specifying a type for that argument (ie, it's a varargs argument,
or there's no prototype in scope at all). There's no need to cast NULL
when using it in comparison with, assignment to, or initialization of a
Now, it could be that NetBSD has committed itself to assuming that null
pointers _are_ all-bits-zero (look at xprt_register, for example, in
lib/libc/rpc/svc.c, which uses memset on an array of pointers), and/or
that all pointer types are "really" just memory addresses and that you
can, for example, memcpy a pointer of one type to a pointer of another
type and get the effect of a cast and assignment; in such a case, you
may be able to mostly get away without casting NULL on NetBSD. But
even if this is so, I think it's a bad idea to actually depend on such
things, especially for an OS that prides itself on doing things right.
I just checked on my NetBSD/alpha machine, and I find that NULL expands
to a bare 0 there. This means that on at least that platform, you _do_
need to cast NULL in unprototyped function arguments, because otherwise
it will pass 32 zero bits (int) instead of 64 zero bits (pointer) and
thereby wreck the rest of the argument list, regardless of what happens
to the pointer itself.
/~\ The ASCII der Mouse
\ / Ribbon Campaign
X Against HTML email@example.com
/ \ Email! 7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B