Avoiding
Undefined Behavior
Learn to identify and prevent the silent killers in C++ programs: out-of-bounds access, invalid iterators, and other edge cases that lead to unpredictable results.
What Is Undefined Behavior?
In C++, undefined behavior (UB) means your program has violated the rules of the language, and the compiler is no longer required to produce any predictable result. The program might crash, produce garbage values, appear to work fine, or even format your hard drive: the standard places no constraints on what happens.
Why UB Is Uniquely Dangerous
Visualizing Memory Access
The Core Rule of Defined Behavior
Categories of Common UB
Defined vs Undefined vs Unspecified
| Defined | Unspecified | Undefined | |
|---|---|---|---|
| Meaning | Standard guarantees exact result | Valid result, but which one is unspecified | No guarantees at all |
| Example | \(1 + 1\) is always \(2\) | Evaluation order of function args | Array out-of-bounds access |
| Danger Level | ✓ Safe | ★ Caution | ✕ Fatal |
| Compiler Freedom | None | Can choose any valid option | Unlimited: may do anything |
How to Prevent UB
.at() for vectors, or validate indices manually before using [].{} or = 0 at declaration.-fsanitize=address,undefined to catch UB at runtime during testing.Example 1: Out-of-Bounds Access
Example 2: Invalid Iterators
Example 3: Dangling References
Iterator Invalidation Rules
| Container | Insert Invalidates | Erase Invalidates |
|---|---|---|
vector |
All (if realloc); at/after point otherwise | At and after erased element |
deque |
All iterators | All, unless erasing only from the ends |
list |
None | Only the erased element |
map/set |
None | Only the erased element |
unordered_map |
All (if rehash); none otherwise | Only the erased element |
Signed Integer Overflow
In C++, signed integer overflow is undefined behavior. If an arithmetic operation on a signed type (like int) produces a value outside the representable range, the compiler is free to assume it never happens and may optimize your code in surprising ways.
Null Pointer Dereference
Common Mistakes
<= instead of < with .size(), accessing one element past the end.push_back() inside a range-for loop on the same vector. Reallocation invalidates all iterators.int x; and reading it before assignment. The value is indeterminate: UB to read it.std::string or std::vector after std::move() without reassigning. The object is in a valid but unspecified state.Defense Strategies Summary
| UB Category | Prevention | Tool Support |
|---|---|---|
| Out-of-Bounds | .at(), bounds checks |
AddressSanitizer |
| Invalid Iterators | Capture erase() return, avoid modify-during-iterate |
Debug iterators (MSVC) |
| Null Dereference | std::optional, null checks |
UndefinedBehaviorSanitizer |
| Signed Overflow | Range checks, use unsigned when appropriate | -ftrapv, UBSan |
| Dangling References | Return by value, smart pointers | ASan, lifetime analysis |
| Uninitialized Reads | Always initialize: int x = 0; or int x{}; |
MemorySanitizer, -Wuninitialized |
Question 1 of 5
What happens when you access vec[vec.size()] on a non-empty std::vector?
[] operator does not perform bounds checking, so this is silent undefined behavior. Only .at() would throw an exception.Question 2 of 5
Consider the following code:
std::vector<int> v = {1, 2, 3, 4, 5};
for (auto it = v.begin(); it != v.end(); ++it) {
if (*it == 3)
v.push_back(6);
}
What is the primary problem with this code?
push_back() triggers a reallocation (because the vector's capacity is exceeded), every iterator, pointer, and reference to the vector's elements is invalidated. The iterator it becomes a dangling iterator, and incrementing or dereferencing it is undefined behavior.Question 3 of 5
Which of the following is well-defined in C++?
Question 4 of 5
Consider the following function:
const std::string& getName() {
std::string name = "Alice";
return name;
}
Why is calling getName() and using its result undefined behavior?
name is a local variable with automatic storage duration. When getName() returns, name is destroyed. The returned reference now refers to deallocated stack memory: a dangling reference. Using it in any way is undefined behavior.Question 5 of 5
You need to remove all even numbers from a std::vector<int>. Which approach is safe?
std::erase_if) is the standard, safe, and most efficient way to remove elements from a sequence container. While iterating backwards (Option D) is also a safe technique, the erase-remove idiom is preferred as it is more idiomatic and often more performant. Options A and B are classic examples of undefined behavior due to iterator invalidation.