Xref: utzoo comp.arch:5327 comp.lang.c:11030
Path: utzoo!attcan!uunet!lll-winken!lll-lcc!ames!umd5!mimsy!chris
From: chris@mimsy.UUCP (Chris Torek)
Newsgroups: comp.arch,comp.lang.c
Subject: Re: null pointers (was: negative addresses)
Message-ID: <12260@mimsy.UUCP>
Date: 30 Jun 88 22:02:40 GMT
References: <226@proxftl.UUCP> <3100003@hpmwtla.HP.COM> <743@award.UUCP>
Followup-To: nowhere
Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742
Lines: 65

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

In article <743@award.UUCP> scott@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  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@mimsy.umd.edu	Path:	uunet!mimsy!chris