[net.unix-wizards] nil pointer dereference response summary and question

silver (01/18/83)

I've gotten numerous letters since my first question, and all the
writers agreed that coding to depend on nil pointers is a NO-NO.
Most thought that trapping it was a good idea, but agreed that 
there is a lot of bad code in existence (yeah!).  But no-one
has yet answered my question:  if I do something like:

int *a = 0, *b = 0;  *a = 1;

Now what is the value of *b?  Zero, or one?  Please mail me
the answer if you know.  Thanks!

dbj.rice@Rand-Relay (03/17/83)

From:  Dave Johnson <dbj.rice@Rand-Relay>

I tried mailing an answer to this, but it seems we are having some trouble
with our CSNet connection, and several of my recent messages have neither
come back to me as general Unix-Wizards messages nor have been returned
as undeliverable.  Who knows where they went...

Anyway, in response to your question, at least for a VAX:

	if I do something like:

		int *a = 0, *b = 0;  *a = 1;

	Now what is the value of *b?  Zero, or one?  

the result will generally be a Bus Error.  The reason for this is that at
location 0 is the register save mask for crt0, which specifies that no
registers be saved - thus there are 16 bits of zeros at address 0.  Since
this is part of the text of the program, rather than its data, it is
generally write-protected (under NMAGIC and ZMAGIC executable formats).
Using an OMAGIC executable (where the text is not write-protected), the
result would that *b would have the value 1 and you would have just written
over the first 4 bytes of the text of your program.  By the way, *a never
had the value 0, since a is an int (which is 32 bits long) and the register
save mask is only 16 bits.  (For those that care, the original value of
*a was 0x08c20000 under Berkeley 4.1; if a and b where short *, the original
value of *a would have been 0.)

The only use of indirecting through a NULL pointer that I have seen in
Unix code is to expect a null character string at location 0.  On a
VAX, this always works because of the register save mask at 0.  It is
really not a good idea to depend on this for reasons of portability, but
there are a lot of Unix programs that do depend on it.

                                        Dave Johnson
                                        Dept. of Mathematical Sciences
                                        Rice University