What Is Undefined Behavior?
Undefined Behavior (UB) means the C standard imposes no requirements on what happens. The program might crash, produce wrong results, appear to work, or summon nasal demons. The compiler is free to do anything.
The Scary Part: UB doesn't always crash. It might work perfectly on your machine, pass all tests, then fail catastrophically in production on a different platform.
The Most Common UB Sources
1. Buffer Overflow
c
2. Null Pointer Dereference
c
3. Use After Free
c
4. Signed Integer Overflow
c
5. Uninitialized Variables
c
6. Double Modification
c
7. Wrong printf Format
c
How to Defend Against UB
1. Compiler Warnings
bash
2. Sanitizers
bash
3. Static Analysis
bash
4. Defensive Coding
c
Summary
| UB Type | Example | Prevention |
|---|---|---|
| Buffer overflow | arr[100] on size-10 array | Bounds checking |
| Null dereference | *NULL | NULL checks |
| Use-after-free | Accessing freed memory | NULL after free |
| Signed overflow | INT_MAX + 1 | Check before arithmetic |
| Uninitialized | Reading garbage | Always initialize |
| Format mismatch | printf("%s", 42) | -Wall warnings |
The golden rule: if the standard says it's undefined, assume the worst. Compile with warnings and sanitizers. Test on multiple compilers.