[comp.sys.amiga.tech] NULL Pointers

nj@magnolia.Berkeley.EDU (...) (10/29/90)

andy@cbmvax.commodore.com (Andy Finkel) writes:

>>If your program breaks when location 0 is non NULL this means
>>you have an unitialized pointer somewhere in your program, and
>>are using memory you did not allocate (ie location 0)

jprad@faatcrl.UUCP (Jack Radigan) said:

>  Uh, according to K&R, NULL is a valid assignment for a pointer, so
>how is it unitialized?

Perhaps "uninitialized" was the wrong word.  The pointer is indeed
initialized to NULL, but it doesn't point to any usable memory (see
below).

>  But, my question is the NULL pointer itself, if NULL is a valid constant,
>then the location NULL should contain nothing either, right?
>  If I somehow missed something so embarrassingly basic, how come I can't
>find it in K&R, which is supposed to be the last word in 'C'?

From [the old pre-ANSI] K&R, p. 97:

"C guarantees that no pointer that validly points at data will contain
 zero...We write NULL instead of zero, however, to indicate more clearly
 that this is a special value for a pointer."

p. 192:

"[Some] compilers currently allow a pointer to be assigned to an
 integer, an integer to a pointer, and a pointer to a pointer of
 another type...This usage is nonportable...However, it is guaranteed
 that assignment of the constant 0 to a pointer will produce a null
 pointer distinguishable from a pointer to any object."

These quotes seem to state pretty clearly that any pointer which
contains 0 does not point to any object.  It is not even true that a
pointer which contains 0 points to location 0 in memory; as the second
quote states, putting "0" into a pointer is different from putting,
say, 0x0ABCFD20 into a pointer--while the latter may (if allowed) be
considered an address, "0" can NEVER be considered an address.

(I seriously doubt this rule was changed by ANSI--my apologies if it was.)

The confusion stems from the fact that the designers of C used "0",
which looks like a number, rather than some special keyword like
"nil", to indicate a pointer that does not point to anything.  Another
byproduct of this is that you can't in fact access location 0 from C
directly--but then, you shouldn't be accessing absolute addresses
(besides 0x00000004) on the Amiga anyway.

There's a better explanation of this on the monthly FAQ post in
comp.lang.c if this wasn't clear.  (I don't have a copy lying around,
otherwise I would have just posted that.)

--
nj			nj@teak.Berkeley.EDU		...!ucbvax!teak!nj