#0Null pointers

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++, the 0 literal can be assigned to any pointer type. It was the preferred method in C++ before introduction of the nullptr 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 the cstdlib header file as 0.

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 be 0.

Sample code

References

  1. C++ Primer, Fifth Edition, chapter 2.3.2. Pointers
  2. The Design and Evolution of C++, chapter 11.2.3. The Null Pointer
  3. Null dereference (OWASP)

All (4 shorts)