01 / 21

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.

C++

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

✕ Silent Corruption
UB may appear to "work" in debug mode but crash in release. It can pass all tests and still be broken.
★ Time Travel
Compilers can assume UB never happens. Code before the UB line may be optimized away or reordered.
★ Security Holes
Buffer overflows and use-after-free are UB. They are the root cause of most C++ security vulnerabilities.

Visualizing Memory Access

int arr[5] [0] [1] [2] [3] [4] 10 20 30 40 50 [5] ??? ✓ Valid: indices 0 through 4 ✕ UB! Undefined Behavior

The Core Rule of Defined Behavior

1
Array/vector access: index must be in range \([0, \text{size})\)
2
Pointer dereference: pointer must be non-null and point to a valid, live object
3
Iterator use: iterator must not be invalidated and must be dereferenceable
4
Integer arithmetic: signed overflow and division by zero are undefined
5
Object lifetime: never use an object after it has been destroyed or moved-from (in undefined ways)

Categories of Common UB

Undefined Behavior Memory Errors Out-of-Bounds Use-After-Free Iterator Errors Invalidated Past-the-End Arithmetic Errors Signed Overflow Div/0 Lifetime and Type Errors Dangling Refs Null Deref

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

1
Check bounds before access. Use .at() for vectors, or validate indices manually before using [].
2
Never modify a container while iterating. Insertions and deletions invalidate iterators. Use index-based loops or collect changes and apply after.
3
Initialize all variables. Reading an uninitialized variable is UB. Use {} or = 0 at declaration.
4
Check pointers before dereferencing. Ensure the pointer is non-null and still points to a live object.
5
Use sanitizers. Compile with -fsanitize=address,undefined to catch UB at runtime during testing.

Example 1: Out-of-Bounds Access

✕ Undefined Behavior
std::vector<int> v = {1, 2, 3}; int x = v[3]; // UB: valid indices are 0, 1, 2
✓ Safe Alternatives
// Option A: bounds-checked access int x = v.at(3); // throws std::out_of_range // Option B: manual check if (index < v.size()) { int x = v[index]; // safe }

Example 2: Invalid Iterators

✕ Undefined Behavior
std::vector<int> v = {1, 2, 3, 4, 5}; for (auto it = v.begin(); it != v.end(); ++it) { if (*it % 2 == 0) v.erase(it); // UB: 'it' is now invalid! }
✓ Safe Version
for (auto it = v.begin(); it != v.end(); ) { if (*it % 2 == 0) it = v.erase(it); // erase returns next valid iterator else ++it; }

Example 3: Dangling References

✕ Undefined Behavior
int& getRef() { int local = 42; return local; // UB: returning reference to local! } int& r = getRef(); std::cout << r; // UB: 'local' no longer exists
✓ Safe Alternatives
// Option A: return by value int getValue() { int local = 42; return local; // copy is fine } // Option B: use a longer-lived object int& getRef(std::vector<int>& v) { return v[0]; // safe if v outlives the reference }

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.

✕ Undefined Behavior
int x = INT_MAX; x = x + 1; // UB: signed overflow // The compiler may assume this is always true: if (x + 1 > x) { ... } // "optimized" to always-true

Null Pointer Dereference

✕ Undefined Behavior
int* ptr = nullptr; int val = *ptr; // UB: dereferencing null
✓ Safe Pattern
int* ptr = findValue(key); if (ptr != nullptr) { int val = *ptr; // safe: checked first } // Even better: use std::optional or references std::optional<int> result = findValue(key); if (result.has_value()) { int val = result.value(); }

Common Mistakes

✕ Off-by-One in Loops
Using <= instead of < with .size(), accessing one element past the end.
✕ Push-Back During Iteration
Calling push_back() inside a range-for loop on the same vector. Reallocation invalidates all iterators.
✕ Uninitialized Variables
Declaring int x; and reading it before assignment. The value is indeterminate: UB to read it.
✕ Returning Local Addresses
Returning a pointer or reference to a stack variable. The memory is gone when the function exits.
✕ Assuming Signed Wraps
Expecting \(\text{INT_MAX} + 1\) to wrap to \(\text{INT_MIN}\). Only unsigned types wrap; signed overflow is UB.
✕ Using Moved-From Objects
Calling operations with preconditions on a 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?

Question 2 of 5

What is the primary problem with this code?

Question 3 of 5

Which of the following is well-defined in C++?

Question 4 of 5

Why is calling getName() and using its result undefined behavior?

Question 5 of 5

You need to remove all even numbers from a std::vector<int>. Which approach is safe?