9.5 — nullptr: pointing at nothing

📘 Chapter 9⏱ about 1 min read✍️ Beginner friendly
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 nowhere

Check 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.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.