What is undefined behavior (UB), and can you give an example of it in C++?

Last updated 21 June 2026

  • Undefined behavior (UB) is code the standard leaves with no requirements. The compiler may do anything: crash, produce wrong output, or appear to work.

  • Examples: out-of-bounds array access, signed overflow (INT_MAX + 1), null/dangling dereference, use-after-free, uninitialized reads, data races.

  • It often works in debug builds but fails when optimized, because compilers optimize assuming UB never happens.

  • https://www.geeksforgeeks.org/cpp/undefined-behavior-c-cpp/
  • https://www.geeksforgeeks.org/cpp/accessing-array-bounds-ccpp/
  • https://www.geeksforgeeks.org/cpp/unspecified-behavior-in-c-c-with-examples/
  • https://www.geeksforgeeks.org/cpp/how-do-sequence-points-relate-to-undefined-behaviour-in-cpp/
  • https://dev.to/naveenadi/argument-evaluation-order-in-c-31e5
  • https://dev.to/million_formula_3be3d915d/c-tips-and-tricks-for-advanced-developers-3mla
  • https://www.geeksforgeeks.org/interview-prep/oops-interview-questions-c-programming/
All C++ interview questions