Referencing NULL pointers

Guy Harris guy at auspex.auspex.com
Tue Jul 11 05:04:34 AEST 1989


>   Apparantly, on other machines this is perfectly valid, since I see
>   quite a lot of this in code created on certain non-sun machines.

No, it's not valid, it just happens to work - and only on *some* other
machines; Suns aren't the only ones that catch attempts to dereference
null pointers.

*Lots* of invalid C constructs happen to work on some implementations,
but that doesn't make them valid; it just makes you unlucky if your code
uses such a construct and you're doing your development on such an
implementation.

>   What can I do about it?

Try checking whether a pointer is null before using it, unless you know
for certain that it won't be null.  Note that the behavior when you
dereference a null pointer isn't guaranteed even if it *doesn't* drop
core - on most implementations where it doesn't, it will probably try to
look at a data item located at location 0 in your address space, and
there are *no* guarantees as to what the locations down there contain. 
In other words, the code

      TYPE	*t = (TYPE *) 0;	/* typedef struct { ... } TYPE; */
      if(t->field == 0)

may test "true" on some such implementations (i.e., "((TYPE *)0)->field"
will be zero, if the location in question at or near location 0 is
zero), and test "false" on other such implementations (i.e., if the
location in question is non-zero).



More information about the Comp.unix.wizards mailing list