01 / 21

Null Pointer
Handling in C++

Learn to recognize null pointers, understand why dereferencing them crashes your program, and master safe pointer patterns that prevent bugs.

C++

What is a Pointer?

A pointer is a variable that stores the memory address of another variable. Instead of holding a value directly, it holds the location where that value lives in memory.

int x = 42 Address: 0x7FF4 int* ptr = &x Stores: 0x7FF4 The Value The Pointer

What is a Null Pointer?

A null pointer is a pointer that points to nothing. It holds a special value (address zero) that signals "I am not currently pointing to any valid memory."

int* ptr = nullptr; // C++11 and later int* old = NULL; // C-style (avoid in modern C++) int* raw = 0; // Also null, but unclear intent

Why Null Pointers Matter

Dereferencing a null pointer means trying to read or write the memory at address zero. The operating system does not allow this, and your program will crash with a segmentation fault.

✕ Crash Risk
Null dereference is the #1 cause of segfaults in C++ programs.
★ Security
Attackers exploit null dereferences to trigger denial of service or worse.
✓ Prevention
Simple checks before you dereference eliminate the entire class of bugs.

The Golden Rule

Have a pointer ptr ptr != nullptr? Yes *ptr Safe! No Handle error Check FIRST, dereference SECOND This one rule prevents most pointer crashes

Dereferencing a Null Pointer

Valid Pointer ptr = 0x7FF4 42 Valid data ✓ *ptr = 42 Null Pointer ptr = nullptr ✕ Address 0x0 SEGFAULT! Program crashes

nullptr vs NULL vs 0

nullptr NULL 0
Type std::nullptr_t Macro (int or void*) int literal
Type-safe? Yes Partial No
Overload ambiguity? Never Can occur Always
C++ Standard C++11+ C / legacy C++ Any
Recommendation ✓ Use this Avoid Avoid

How to Check for Null

1
Explicit comparison: Write if (ptr != nullptr) for maximum clarity. This tells the reader exactly what you intend.
2
Implicit boolean conversion: Write if (ptr). A non-null pointer converts to true, a null pointer converts to false. Shorter, but less explicit.
3
Negation for null check: Write if (!ptr) to test whether the pointer is null. Equivalent to if (ptr == nullptr).
4
Guard clause pattern: Return early if null: if (!ptr) return; then safely use *ptr on the lines that follow.

Step-by-Step Safe Pattern

1
Initialize every pointer. Either point it at a valid object or set it to nullptr. Never leave it uninitialized.
2
Check before dereferencing. Always test if (ptr != nullptr) or if (ptr) before using *ptr or ptr->member.
3
Set to nullptr after delete. After delete ptr;, immediately write ptr = nullptr; to prevent a dangling pointer.
4
Prefer smart pointers. Use std::unique_ptr or std::shared_ptr which manage lifetime automatically and reduce manual null checks.

Example 1: Basic Null Check

#include <iostream> void printValue(int* ptr) { if (ptr != nullptr) { std::cout << "Value: " << *ptr << std::endl; } else { std::cout << "Pointer is null!" << std::endl; } } int main() { int x = 42; printValue(&x); // Output: Value: 42 printValue(nullptr); // Output: Pointer is null! }

Example 2: Guard Clause

void processOrder(Order* order) { // Guard clause: bail out early if null if (!order) { std::cerr << "Error: null order" << std::endl; return; } // Safe to use from here onward order->validate(); order->ship(); std::cout << "Order shipped!" << std::endl; }

Example 3: Delete and Reset

int* data = new int(100); // ... use *data ... delete data; // Free the memory data = nullptr; // Reset to null immediately! // Later in the code, safe to check: if (data) { std::cout << *data; // Will NOT run: data is nullptr }
Before delete data: 0xAB00 After delete (danger!) data: 0xAB00 (freed!) After reset (safe) data: nullptr

Modern C++: Smart Pointers

Smart pointers automatically manage memory. When the pointer goes out of scope, the memory is freed. This eliminates manual delete and reduces null/dangling pointer bugs dramatically.

unique_ptr
Sole ownership. Only one pointer owns the resource. Cannot be copied, only moved. Lightweight and fast.
shared_ptr
Shared ownership. Multiple pointers can share one resource. Uses reference counting. Freed when count hits zero.
weak_ptr
Non-owning observer. Points to a shared resource without preventing it from being freed. Must check before use.
#include <memory> auto p = std::make_unique<int>(42); std::cout << *p; // 42, no manual delete needed!

Null in Data Structures

Null pointers appear constantly in linked lists, trees, and graphs. The null value marks the end of a structure or an absent child.

10 head 20 30 nullptr end Linked list: nullptr signals the end of the chain Always check next != nullptr before traversing

Common Mistakes

✕ Uninitialized Pointer
Declaring int* ptr; without assigning it. The pointer contains garbage: a random address that may or may not crash.
✕ Forgetting Null Check
Calling ptr->method() without first verifying ptr != nullptr. Works until someone passes null, then crashes in production.
✕ Dangling After Delete
Using delete ptr; but not setting ptr = nullptr; afterward. The pointer still holds the old address, which is now freed memory.

Summary: Safe vs Unsafe

Pattern Unsafe Safe
Initialization int* p; int* p = nullptr;
Dereference cout << *p; if (p) cout << *p;
After delete delete p; delete p; p = nullptr;
Ownership raw new/delete unique_ptr / shared_ptr
Null constant NULL or 0 nullptr

Question 1 of 5

What happens when you dereference a null pointer in C++?

Question 2 of 5

Which is the preferred way to represent a null pointer in modern C++ (C++11 and later)?

Question 3 of 5

What is the problem with this code?

Question 4 of 5

Which modification makes this function safe against null pointers?

Question 5 of 5

Which smart pointer type provides sole ownership and automatically frees memory when it goes out of scope?