A pointer to null, also known as a null pointer, is created by initializing a pointer object to 0
, NULL
, or in the case
of C++ nullptr
. A null pointer does neither point to an object nor to valid memory, and as a consequence dereferencing or accessing the
memory pointed by such a pointer is undefined behavior.
int deref() {
int* ptr = 0;
return *ptr; // Noncompliant: deference of a null pointer
}
In addition to using the *
operator, accessing a member of a structure (using →
) or an element of an array (using
[]
) also leads to dereference of the pointer, and causes undefined behavior if performed on a pointer to null.
int subscript() {
int* ptr = 0;
return ptr[2]; // Noncompliant: subscript operator used on null pointer
}
struct Aggregate {
int x;
int y;
};
int memberAccess() {
struct Aggregate* ptr = 0;
return ptr->x; // Noncompliant: member access on a null pointer
}
Finally, invoking a function pointer that holds a null value, dereferences the pointer, and too results in undefined behavior.
void call() {
void (*func)(int) = NULL; // func is a pointer to a function
func(10); // Noncompliant: the invocation of a null function pointer
}