Are 0 pointers more valid than invalid pointers? (Re: effect of free())

Doug Gwyn gwyn at smoke.BRL.MIL
Sat Sep 9 19:17:38 AEST 1989


In article <8385 at boring.cwi.nl> dik at cwi.nl (Dik T. Winter) writes:
-In article <192700004 at eriador> andyj at eriador.prime.com writes:
- >       Note that the compiler makes a special check for
- >       comparison or assignment with a null pointer constant, since a null 
- >       pointer would give an addressing failure if it went through the special
- >       instructions.
-Is this correct?  Given the following part of a program:
-	int *a, *b;
-	a = 0;
-	b = 0;
-	if (a == b) ....
-If the above explanation states what I think it states this will trap.
-Is this correct behaviour in ANSI C?  (There is no comparison with
-constant 0 involved.)

I don't think Andy really meant to say "null pointer constant".  The
proposed standard requires comparisons against null pointers (stored
in variables) to work as well as ones against null pointer constants,
which the compiler can indeed recognize and treat specially.

An implementation that has a problem with this should use the trick
I've recently described, so that null pointers are always valid as
far as the underlying machine is concerned.

-An easy way out in this case is available on machines that have VM.
-All invalid pointers are unmapped in user space, but NULL is mapped.
-When a dereference of NULL occurs this will trap a page fault
-the OS will see as a dereference of NULL.  So, completely according
-to ANSI C, using an invalid pointer will trap, except when it is
-NULL, than a trap only occurs on a dereference.

I agree that the null pointer representation should be a mapped value.
I don't see that anything special needs to be done by the OS, though.
ANSI C does not REQUIRE that dereferencing a null pointer trap; it
merely permits it.



More information about the Comp.lang.c mailing list