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.
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.
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."
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.
The Golden Rule
Dereferencing a Null Pointer
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
Step-by-Step Safe Pattern
Example 1: Basic Null Check
Example 2: Guard Clause
Example 3: Delete and Reset
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.
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.
Common Mistakes
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
Consider this code:
What is the problem with this code?
Question 4 of 5
Consider this function:
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?