Dereferencing a pointer to 0 in C
Solution 1:
C does not prohibit dereferencing the null pointer, it merely makes it undefined behavior.
If your environment is such that you're able to dereference a pointer containing the address 0x0
, then you should be able to do so. The C language standard says nothing about what will happen when you do so. (In most environments, the result will be a program crash.)
A concrete example (if I'm remembering this correctly): On the 68k-based Sun 3 computers, dereferencing a null pointer did not cause a trap; instead, the OS stored a zero value at memory address zero, and dereferencing a null pointer (which pointed to address zero) would yield that zero value. That meant, for example, that a C program could treat a null pointer as if it were a valid pointer to an empty string. Some software, intentionally or not, depended on this behavior. This required a great deal of cleanup when porting software to the SPARC-based Sun 4, which trapped on null pointer dereferences. (I distinctly remember reading about this, but I was unable to find a reference; I'll update this if I can find it.)
Note that the null pointer is not necessarily address zero. More precisely, the representation of a null may or may not be all-bits-zero. It very commonly is, but it's not guaranteed. (If it's not, then the integer-to-pointer conversion of (void*)0
is non-trivial.)
Section 5 of the comp.lang.c FAQ discusses null pointers.
Solution 2:
How do people actually use 0x0 when it's needed?
By either:
- writing the required code in assembly language, or
- writing the code in C and verifying that their compiler generates correct assembly language for the desired operation