In computing, a null pointer has a value reserved for indicating that the pointer does not refer to a valid object. Programs routinely use null pointers to represent conditions such as the end of a list of unknown length or the failure to perform some action; this use of null pointers can be compared to nullable types and to the Nothing value in an option type.
A null pointer should not be confused with an uninitialized pointer: A null pointer is guaranteed to compare unequal to any pointer that points to a valid object. However, depending on the language and implementation, an uninitialized pointer may not have any such guarantee. It might compare equal to other, valid pointers; or it might compare equal to null pointers. It might do both at different times.
In C, two null pointers of any type are guaranteed to compare equal. The macro NULL
is defined as an implementation-defined null pointer constant, which in C99 can be portably expressed as the integer value 0
converted implicitly or explicitly to the type void*
.
Dereferencing the NULL pointer typically results in an attempted read or write from memory that is not mapped - triggering a segmentation fault or access violation. This may represent itself to the developer as a program crash, or be transformed into an exception that can be caught. There are, however, certain circumstances where this is not the case. For example, in x86-real mode, the address 0000:0000 is readable and usually writable, hence dereferencing the null pointer is a perfectly valid but typically unwanted action that may lead to undefined but non-crashing behaviour in the application. Note also that there are occasions when dereferencing the NULL is intentional and well defined; for example BIOS code written in C for 16-bit real-mode x86 devices may write the IDT at physical address 0 of the machine by dereferencing a NULL pointer for writing. It is also possible for the compiler to optimize away the `NULL` pointer dereference, avoiding a segmentation fault but causing other undesired behavior.