How do you detect and prevent undefined behavior?
Short 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).
Advertisement
AModel 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.cppReal-world example
Running tests under UBSan and ASan in CI catches out-of-bounds and overflow bugs before release.
Likely follow-ups
- What does UBSan detect? | What coding practices prevent UB?
Related topics