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.