Referencing NULL pointers

CME Ned Nowotny ned at pebbles.cad.mcc.com
Tue Jul 18 05:40:52 AEST 1989


In article <1382 at bruce.OZ> mmcg at bruce.OZ (Mike  Mc Gaughey) writes:
=>vohra at uts.amdahl.com (Pavan Vohra) [11 Jul 89 07:35:39 GMT]:
=>> 
=>> I would say that the code is valid.
=>> 
=>> Try a rewrite: "x= ((struct somestruct *)0)->somefield".
=>
=>Sure it's valid.  It's just that the pointer value you are using does
=>not point to any valid object (like a variable, or some heap space, or
=>writable code) and hence may not point to allocated memory.  Result:
=>segmentation violation.  If you want to hardwire a particular address,
=>that's up to you - maybe some useful information is there - but don't
=>bitch when it doesn't work on someone else's machine.
=>
=>BTW: There _is_ a way to guarantee that you have a valid pointer -
=>it's called malloc :-)
=>

The argument over whether or not a C compiler should allow dereferencing of
0 (NULL) or any other numeric constant purporting to be an address is unrelated
to the question of portability.  Of course, dereferencing of 0 (or any other
numeric constant) is not portable and it certainly is not a conforming ANSI-C
program.  However, there are environments where addresses can be represented
by numeric constants and there really is something important at address 0.  If
the compiler can detect dereferencing of 0, it should print a warning, but it
should not prohibit the operation.  This is even true of C compilers that
think they know the environment for which they are compiling.  After all, only
the loader really knows anything about the valid memory map.  I may use a
compiler on one machine to compile code I will use on another machine (as
long as the processors and any co-processors are compatible.)  Admittedly,
compiler venodrs can make this impossible, but it isn't required.  In summary,
there may very well be validity to dereferencing 0, but if you do it
intentionally it must be presumed that you know what you are doing.

Ned Nowotny, MCC CAD Program, Box 200195, Austin, TX  78720  Ph: (512) 338-3715
ARPA: ned at mcc.com                   UUCP: ...!cs.utexas.edu!milano!cadillac!ned
-------------------------------------------------------------------------------
"We have ways to make you scream." - Intel advertisement in the June 1989 DDJ.



More information about the Comp.unix.wizards mailing list