NULL question not in FAQ

Henry Spencer henry at zoo.toronto.edu
Thu Mar 28 04:06:46 AEST 1991


In article <1991Mar26.235643.4498 at ux1.cso.uiuc.edu> phil at ux1.cso.uiuc.edu (Phil Howard KA9WGN) writes:
>Given that the compiler is supposed to translate the constant "0" to the
>appropriate value for a NULL pointer on the machine type, how does one
>get a pointer value whose representation happens to be all zeroes, but
>is a non-NULL pointer?

I assume you're talking about a machine where such a thing is possible.
On many machines an all-zeros pointer is a null pointer.

This will work:

	char *p;

	memset(&p, 0, sizeof(p));

Note that an all-zeros pointer might cause a core dump whenever you try
to compare it or assign it, never mind follow it.  Turning an arbitrary
bit pattern into a pointer is fraught with peril.

>Are all of these equivalent or are any differnt?
>    p = ( (char *) 0 );
>    p = ( (char *) 00 );
>    p = ( (char *) 0x0 );
>    p = ( (char *) 0x00 );
>    p = ( (char *) 1-1 );

Apart from the precedence error in the last one, they are all equivalent.
Any zero-valued constant expression turns into a null pointer when used
in a pointer context.

>Suppose I do this:
>    char *p;
>    int i;
>    p = NULL;
>    i = (int) p;
>Will I get a value of zero in "i" always, regardless of the way the
>machine type represents a NULL?

No; the value you get is *totally* implementation-dependent.  There is
absolutely no guaranteed relationship between the representation of
integer zero and the representation of null pointers.  The 0-to-null
conversion is entirely a compile-time phenomenon.

>For low level code, e.g. drivers and such, where portability and machine
>independence are not issues, it would still be nice to be able to cast
>address values into pointers as desired...

There is nothing stopping you from doing this, but you have to have
implementation-specific knowledge of what the results will be.  It's
not portable.
-- 
"[Some people] positively *wish* to     | Henry Spencer @ U of Toronto Zoology
believe ill of the modern world."-R.Peto|  henry at zoo.toronto.edu  utzoo!henry



More information about the Comp.lang.c mailing list