9.5 — nullptr: pointing at nothing
Read one box at a time. No rush.
The empty pointer#
A pointer can point at nothing. We write that as nullptr.
C++
int* p { nullptr }; // points nowhereCheck before using#
Dereferencing nullptr crashes the program (or worse).
C++ — wrong ✗
int* p { nullptr };std::cout << *p; // crash!C++ — right ✓
if (p != nullptr){ std::cout << *p;}You can also write simply if (p) — a pointer counts as true when it isn't nullptr.
Watch out
Always initialize pointers. An uninitialized pointer holds a random address, and using it is undefined behavior. If you have nothing to point at yet, use nullptr.
Dangling pointers#
A pointer to a variable that no longer exists is dangling:
C++ — wrong ✗
int* makeBad(){ int local { 5 }; return &local; // local is destroyed when the function ends!}The pointer points at a box that's been thrown away. Never return the address of a local variable.
Tip: press ← / → to move between lessons, / to search.