Undefined behavior (UB) means the standard places no requirements on what happens. The program may crash, appear to work, or behave differently after recompile—unlike defined errors in Java.
Common UB sources
- Out-of-bounds array access
- Signed integer overflow
- Dereferencing invalid pointers
- Data races without synchronization
- Reading uninitialized automatic variables
Implementation-defined vs unspecified
Some behavior varies by platform but is constrained; UB has no guarantees—treat it as a bug always.
Important interview questions and answers
- Q: Why care about UB if it works?
A: Optimizers assume UB never happens—"working" code can break under-O2or on another compiler. - Q: Rust vs C on UB?
A: Rust safe code avoids most UB at compile time; C requires discipline and tools.
Self-check
- Is signed int overflow defined in C?
- What happens after free() if you dereference the pointer?
Pitfall: Code with UB may work in debug builds then break under -O2—treat sanitizer warnings and compiler diagnostics seriously, unlike forgiving dynamic languages.
Interview prep
- Why UB matters if code works?
Optimizers assume UB never happens—working debug code can break in release builds or on other compilers.
- Signed overflow?
Undefined in C—use unsigned types or check before arithmetic if wrap semantics are needed.