C++ › Undefined Behavior

How do you detect and prevent undefined behavior?

Intermediate

Answer

Prevent UB with safe practices: initialize variables, use containers/at()/bounds checks, smart pointers and RAII, avoid manual casts, and enable warnings (-Wall -Wextra). Detect it with sanitizers (UndefinedBehaviorSanitizer, AddressSanitizer, ThreadSanitizer), static analysis (clang-tidy, cppcheck), and thorough tests run under these tools in CI.
g++ -fsanitize=undefined,address -g prog.cpp
Real-world example Running tests under UBSan and ASan in CI catches out-of-bounds and overflow bugs before release.

Common follow-ups: What does UBSan detect? | What coding practices prevent UB?