Referencing NULL pointers

Barry Margolin barmar at think.COM
Tue Aug 29 08:10:05 AEST 1989


In article <10862 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn) writes:
>In article <9838 at xanth.cs.odu.edu> kremer at cs.odu.edu (Lloyd Kremer) writes:
>>	p = 0;  /* integer variable that happens to be set to zero */
>>	data = *(int *)p;  /* no constant expression in this line */
>>I would think the "promotion to nil pointer" rule would not apply here.
>Correct, as Chris has already pointed out.  However I think there are
>enough requirements imposed on converting between integers and pointers
>that if you allow the above you'll also have to make the null pointer a
>funny bit pattern, with resulting higher overhead than most people would
>think necessary in that environment.  I don't have a formal proof though..

Why?  You'd only need a funny bit pattern for the null pointer if you
want to guarantee a runtime error when dereferencing the null pointer,
or if some library routine might return a pointer to location 0 that
must be distinguished from NULL.

Such a library routine would have to be implementation-dependent, of
course; malloc, for example, could never return a pointer that
happened to have the same representation as the null pointer.  But if
there's some implementation-specific data at location 0, and the
implementation uses a pointer to 0 as the null pointer, there's no
reason you couldn't use
	ptr = 0;
	foo = *ptr;
to access it.  This code is non-portable, but so is the fact that this
particular piece of data is at location 0.

Barry Margolin
Thinking Machines Corp.

barmar at think.com
{uunet,harvard}!think!barmar



More information about the Comp.lang.c mailing list