A null pointer is a pointer that doesn't point to any object. A null pointer is not guaranteed to be the same as a pointer to memory address 0 (but it often is). There are several ways to obtain a null pointer:
- The
nullptr
literal. It's special type,nullptr_t
, converts to any other pointer type. It was introduced in C++ 11 and is the preferred method to initialize null pointers. - The
0
literal. In C++, the0
literal can be assigned to any pointer type. It was the preferred method in C++ before introduction of thenullptr
literal. - Value initialization. Value initializing a pointer sets its value to null automatically. Both
()
and{}
have the same effect on pointer initialization. NULL
macro. It was inherited from the C language, and some programmers still use it (you shouldn't). It is defined in thecstdlib
header file as0
.
Here's a few key aspects you should remember when working with null pointers in C++:
- Dereferencing a null pointer is undefined behavior. Always check your pointers before accessing the pointed objects.
- An uninitialized pointer is not a null pointer. It's garbage, in the same way as any other built-in type that's left uninitialized.
- It's illegal to assign an
int
variable to a pointer, even if the variable's value happens to be0
.
Sample code
References
- C++ Primer, Fifth Edition, chapter 2.3.2. Pointers
- The Design and Evolution of C++, chapter 11.2.3. The Null Pointer
- Null dereference (OWASP)