Modern C++ • C++20 baseline
Undefined Behavior, Object Lifetimes, and Valid Programs
Recognize invalid operations whose results cannot be made portable by testing.
The C++ abstract machine imposes no requirements after undefined behavior. Common causes include out-of-bounds indexing, use-after-free, signed overflow, invalid iterator use, and data races. Optimizers may assume these situations never occur, so a bug can behave differently between debug and release builds.
Key points
- Sanitizers can reveal executed defects but cannot prove their absence.
- Object lifetime rules matter even when an address still appears readable.
Example
#include <vector>
int first_or_zero(const std::vector<int>& values) {
if (values.empty()) {
return 0;
}
return values.front();
}
What to expect
The function checks emptiness before accessing the first element.
Practice exercise
Write tests for an empty vector and a one-element vector; run them with address and undefined-behavior sanitizers.
Key idea: Keep every access within a live object’s valid range and lifetime.