null pointers (was: negative addresses)

Guy Harris guy at gorodish.Sun.COM
Fri Jul 1 10:02:35 AEST 1988


> 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.

Only if the implementor was ignorant, in which case they shouldn't be trying to
implement C without having somebody around who *does* know the language.

You don't have to guarantee that that location is inaccessible, you merely have
to guarantee that no object that a C program can refer to is at that address.
If "malloc" will never return a pointer to an object at location 0, and if no
static or global data or code defined in a C program will ever be put at
location 0, and if no data object on the stack will be at location 0, this is
sufficient.

If it is truly impossible to arrange for this to happen, what you can do is:

	1) define the format of a null pointer to be, say, 0xFFFF;

	2) have the C compiler properly handle null pointers.

Thus, the C code

	char *p;

	p = 0;

would generate machine code something like

	move.i	#ffff,p

(i.e., store the bit pattern 0xFFFF into "p"), and the C code

	char *p;

	if (p == 0)

or

	char *p;

	if (!p)

would generate machine code something like

	cmp.i	#ffff,p
	bne	1f
	(code inside "if")
1:

(i.e., compare "p" against the bit pattern 0xFFFF; if it's equal, the pointer
is "equal to zero", or null).

Given that, NULL should be defined as 0, not -1.



More information about the Comp.lang.c mailing list