Dereferencing a pointer to 0 in C Dereferencing a pointer to 0 in C c c

Dereferencing a pointer to 0 in C


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.


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


The statement:

char * x = 0;

does not necessarily put 0x0 into x. It puts the defined null pointer value for the current architecture and compiler into x.

Now, in practical terms, all compilers / processors observed in common use do end up putting 32 (or 64) 0 bits in a row in a register or storage location in response to that statement, so, so if memory address 0 is useful, then, as others have indicated, you are stuck using formally undefined behavior. However, in once upon a time there was hardware out there for which a 'null pointer' was some bit pattern that was not all zeros, and, who knows, there may be again.