null pointers (was: negative addresses)

Chris Torek chris at mimsy.UUCP
Fri Jul 1 08:02:40 AEST 1988


>In article <3100003 at hpmwtla.HP.COM> jeffa at hpmwtla.HP.COM (Jeff Aguilera)
asks:
>>why do some systems have #define NULL (-1) in stdio? 

In article <743 at award.UUCP> scott at award.UUCP (Scott Smith) answers:
>K&R p97: "C guarantees that no pointer that validly points
>at data will contain zero" ...

(A better place is the appendix, which is more explicit.)

>The reason some systems have #define NULL (-1) in stdio is becuase zero
>*can* be a pointer to valid data (as is the case in my micro). In this
>case, NULL is simply changed to be a value that can't be a valid pointer
>on that particular system.

Or, to simplify it:

	Some systems have `#define NULL (-1)' in <stdio.h> because
	some systems are broken.

If location zero is a valid data address, the compiler must take
care to ensure that either nil pointers are not the all-zero bit
pattern, or that something which is never accessed from C is stored
in location zero.

Given the C code

	main()
	{
		char *p = 0;

		if (p) *p = 0;
	}

the following pseudo-assembly is legal and correct:

	main_::
		create_frame

		move	#0xff00,-4(stack)	| p = (char *)0

		move	-4(stack),r0
		cmp	r0,#0xff00		| if (p)
		branch	notequal,$1
		move	#0,0(r0)		| *p = 0
	$1:

		destroy_frame

		return

Notice how pointer assignments and comparisons with `0' turn into
assignments and comparisons with a magic nil pointer.  Whether that
nil pointer's value is in fact zero is not determined, but IN THE
SOURCE LANGUAGE THAT NIL POINTER IS WRITTEN AS IF IT WERE THE INTEGER
ZERO.  (The dpANS also allows (void *)0.)

-----------------------------------------------------------------------
In C, NULL may or may not be in fact zero, but it is *written* as zero.
-----------------------------------------------------------------------

(Nil pointers also have types, and cannot be correctly discussed without
also mentioning their types, but this is the important part.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list