Loading lessons...
Null Pointers
Null Pointers
A pointer usually points to something real, but sometimes it should point to nothing. C++ calls that a null pointer.
Declaring a null pointer
#include <iostream>
using namespace std;
int* ptr = nullptr; // points at nothing
nullptr is the modern keyword meaning "no address" (introduced in C++11). Old code may use 0 or NULL instead, but nullptr is the type-safe choice.
Check before dereference
int* ptr = nullptr;
if (ptr != nullptr) {
cout << *ptr << endl; // safe
}
The guard ptr != nullptr makes sure we do not touch memory when a pointer has no target.
Dereferencing null is undefined behavior
int* ptr = nullptr;
cout << *ptr << endl; // danger!
A null pointer holds address 0, which is owned by the operating system, not your program. Reading through it is undefined behavior - the program crashes or prints garbage.
Dangling pointers
A closely related trap is the dangling pointer: the address is still stored, but the memory was already freed.
int* ptr = new int(42);
delete ptr; // memory is released
cout << *ptr << endl; // dangling!
Using a dangling pointer is undefined behavior too. If you manage memory by hand, set the pointer back to nullptr after a delete.
Safe habits
- Start a pointer at
nullptrwhen it has no object yet. - Check
ptr != nullptrbefore dereferencing. - After
delete, point the pointer atnullptr.
TL;DR
nullptrmeans "points at no address".- Check
ptr != nullptrbefore dereferencing. - Dereferencing null is undefined behavior (a crash).
- A pointer to freed memory is called dangling.
- After a manual delete, set the pointer back to
nullptr.