Undefined Behavior in C
Undefined behavior (UB) means the standard imposes no requirements — the program may crash, corrupt data, or appear to work until the compiler upgrade. The rogues' gallery: out-of-bounds access, null dereference, use-after-free, signed integer overflow, data races, use of uninitialized values, and strict-aliasing violations.
Modern compilers exploit UB for optimization (assuming it never happens), so violations manifest as impossible behavior — removed null checks, infinite loops that exit. Treat every -Wall warning as a UB suspect, run UBSan regularly, and internalize that in C, wrong code has no defined meaning to fall back on.
No requirements means anything
UB isn't guaranteed-crash — compilers assume it absent and optimize accordingly, producing behavior that looks haunted.
Know the classics
Buffer overflows, null derefs, use-after-free, signed overflow, data races, uninitialized reads, aliasing breaks — memorize the list.
Optimizers weaponize it
if (p) *p with p null may vanish entirely (compiler proved dereference implies non-null) — checks evaporate after violations.
Detect systematically
-Wall -Wextra plus -fsanitize=undefined,address in testing turns most UB into loud, located failures.
#include <stdio.h> int main(void) { int a[2] = {1, 2}; printf("%d\n", a[0]); /* a[5] here would be undefined behavior: no guaranteed crash, no guaranteed value. */ return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.