Topics / C Programming / Q14
What is undefined behaviour? Give examples.
Short answer: Undefined behaviour (UB) means the C standard places no requirements on what happens. The program may crash, give a wrong result, or appear to work. Worse, the optimiser assumes UB never happens and transforms code on that basis, so a bug can be invisible at -O0 and appear at -O2, or remove a safety check entirely.
Common examples
| Example | Why it is UB |
|---|---|
INT_MAX + 1 |
signed integer overflow (unsigned wraps and is defined) |
*p where p is NULL, freed, or out of scope |
invalid pointer dereference |
int x; return x + 1; |
reading an uninitialised automatic variable |
a[10] for int a[10] |
out-of-bounds access |
1 << 32 on a 32-bit int, x << -1 |
shift by ≥ width or negative |
i = i++; |
unsequenced modifications |
accessing a float through an int * |
strict aliasing violation |
modifying a string literal: char *s = "hi"; s[0] = 'H'; |
literals may be in read-only memory |
| returning without a value from a non-void function and using the result | missing return |
INT_MIN / -1, x / 0 |
division overflow / by zero |
How the optimiser exploits UB
int check(int x)
{
if (x + 1 < x) /* intended overflow check */
return -1; /* compiler: signed overflow can't happen, so this is never true */
return x + 1; /* the check is deleted */
}
Correct: if (x == INT_MAX) return -1;.
Related categories (often asked together)
- Unspecified behaviour: one of several valid outcomes, not documented: order of evaluation of function arguments (
f(a(), b())). - Implementation-defined behaviour: the compiler must choose and document:
sizeof(int), right shift of negative numbers, whethercharis signed.
Finding UB: -Wall -Wextra, -fsanitize=undefined,address on a host build of your code, static analysers (cppcheck, clang-tidy, PC-lint, Polyspace), and MISRA C rules, many of which exist precisely to avoid UB.