Advertisement
Intermediate C++, Undefined Behavior

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).

Save C++ mock interview
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.cpp
Real-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