AdvancedLesson 17 of 18
Undefined Behavior and Typical Pitfalls – C++
Dangling references, iterator invalidation, overflows – and how sanitizers find them.
Undefined behavior (UB) means: the C++ standard makes no statement about what happens. The program may work, crash, or deliver seemingly correct but wrong results – and the optimizer may assume that UB never occurs. The most common causes in everyday code:
#include <string>
#include <string_view>
#include <vector>
// 1) Dangling reference: reference to a destroyed object
const std::string& schlecht() {
std::string s = "local";
return s; // UB: s is gone after the return
}
// 2) Dangling string_view: the temporary object dies at the end of the line
std::string_view sv = std::string("temporary"); // sv points into nothing
// 3) Iterator invalidation
void iterator_falle() {
std::vector<int> v{1, 2, 3};
for (int x : v)
if (x == 2) v.push_back(4); // UB: push_back can move the memory
}
// 4) Out-of-bounds access, uninitialized values
void grenzen() {
std::vector<int> v(3);
int a = v[10]; // UB (v.at(10) would throw instead)
int b; // not initialized
int c = b + a; // UB: reading b
(void)c;
}Here is how to do it right: return values instead of references to locals, hold ownership by value or smart pointer, do not modify containers while iterating, and check bounds.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
std::string gut() {
std::string s = "local";
return s; // return by value (RVO/move, no copying)
}
int main() {
std::string s = gut();
std::string_view sv = s; // ok: s outlives sv
std::vector<int> v{1, 2, 3};
v.push_back(4); // modification BEFORE iterating
std::erase_if(v, [](int x) { return x == 2; }); // safe deletion
for (int x : v) std::cout << x << ' '; // 1 3 4
std::cout << sv << '\n';
}- Signed overflow:
INT_MAX + 1is UB; onlyunsignedoverflows in a defined way (wraparound) - Dereferencing null pointers and access after
delete(use-after-free) - Data races: two threads write the same variable without synchronization
- Slicing: polymorphic object copied by value – not UB, but almost always a bug
- Lambda capture by reference beyond the lifetime of the variable
- Shifting by too many bits or division by 0
TipCompile debug builds with
-fsanitize=address,undefined -g: AddressSanitizer finds memory errors (dangling, overflow, use-after-free), UBSan finds signed overflow among other things. For threads there is -fsanitize=thread. In addition: -Wall -Wextra -Wpedantic -Wconversion and static analysis with clang-tidy.WarningA program that "runs on my machine" can still contain UB – tomorrow with a different compiler or optimization level it breaks. Never rely on tests alone; use sanitizers and warnings.