What a null pointer is
A null pointer is a pointer that does not point to any object or function. The C standard guarantees that a null pointer compares unequal to any pointer to an object or function. Programmers use it as a marker for “no valid address here.”
How you get a null pointer
You create a null pointer by assigning a null pointer constant to a pointer. The usual choices are NULL, 0, and (void *)0:
#include <stddef.h>
int *a = NULL;
int *b = 0;
int *c = (void *)0;
All three set the same null pointer value. Most C code uses NULL because it reads most clearly. Readers who see both forms often ask, why use null instead of 0? The main reason is clarity, since NULL tells the reader that a pointer is involved.
Most systems store a null pointer as all zero bits, but the C standard does not require that. Your code should never rely on the bit pattern.
Testing for a null pointer
Check a pointer before you use it:
if (p == NULL) {
/* p points to nothing. */
}
if (p != NULL) {
/* p is not null, so the check has passed. */
}
A non-null pointer is not automatically valid. It might point to memory that has been freed, so it is still your job to know where it points.
A pointer you do not initialize is not null
A local pointer that you do not initialize holds an indeterminate value. It is not null, and it may look like any address:
int *p; /* Indeterminate: could hold any value. */
int *q = NULL; /* Known: points to nothing. */
Initialize pointers when you declare them, so you always know their state.
Dereferencing a null pointer
Reading or writing through a null pointer is undefined behavior. The program may crash, give wrong results, or seem to work for a while. Dereferencing a null pointer is a common answer to the question what can cause a SEG fault? In practice, the access often goes to an address the program is not allowed to use.
Where null pointers come from
Library functions return a null pointer to signal failure. For example, malloc returns a null pointer if it cannot get the memory, and fopen returns a null pointer if it cannot open a file. Check the result before you use it:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *numbers = malloc(10 * sizeof *numbers);
if (numbers == NULL) {
fprintf(stderr, "Could not allocate memory\n");
return 1;
}
/* Use numbers here. */
free(numbers);
return 0;
}
Summary
- A null pointer points to no object or function.
- You create one with
NULL,0, or(void *)0. - Check a pointer for null before you use it.
- Dereferencing a null pointer is undefined behavior.