Undefined Behavior
Undefined behavior is any situation where the C standard imposes no requirements on what the program does. Because the compiler is allowed to assume it never happens, a single instance can change code far away from the mistake.
Detailed Explanation
Read the standard's own words: on encountering undefined behavior, the document "imposes no requirements". Not "the result is unpredictable", not "the program crashes". No requirements. Anything the translated program does satisfies the standard.
The reason C has this category at all is a bargain about checks. Bounds checking every array access, or trapping every signed overflow, costs cycles on every operation. C was designed for machines where those cycles mattered, so instead of defining a behavior, the standard declares the situation off limits and hands the responsibility to you. In exchange the compiler emits the fast instruction with no guard.
Here is the part that surprises people. The compiler does not only skip the check. It reasons forward from the assumption that undefined behavior never occurs, and that reasoning deletes code you wrote.
Consider if (x + 1 < x) return OVERFLOW; for a signed int x. Signed overflow is undefined, so x + 1 < x can never be true in any program the compiler is required to handle. So the branch is dead. So it is removed. Your overflow check disappears at -O2 and the function returns the wrong answer only on the inputs you were trying to guard against.
The same logic runs backwards through the code. If you dereference a pointer and then test it for null, the compiler concludes the pointer was non-null at the dereference, and therefore non-null at the later test, and removes the test. People call this "time-travel", though nothing travels: it is one consistent deduction.
The common instances are worth memorising:
- Signed integer overflow.
INT_MAX + 1. Unsigned overflow is defined and wraps modulo2^N. - Out-of-bounds access. Reading or writing
a[n]on anint a[n], or forming a pointer more than one past the end. - Use after free and double free. The pointer value itself becomes indeterminate after
free, so even copying it is undefined. - Null pointer dereference.
- Reading an uninitialized object whose address was never taken (an indeterminate value that may be a trap representation).
- Strict aliasing violations. Accessing an object through a pointer to an incompatible type. Character types and
memcpyare the escape hatch. - Data races. Two threads touching the same object with at least one write and no synchronization.
- Shifting by a negative amount or by at least the operand's width, and left-shifting a negative value.
Distinguish three neighbouring terms:
| Category | Guarantee | Example |
|---|---|---|
| Undefined | none at all | signed overflow |
| Unspecified | one of several valid outcomes, not documented | order of function argument evaluation |
| Implementation-defined | one of several valid outcomes, documented by the compiler | whether plain char is signed |
You cannot test your way out of undefined behavior, because a build that happens to work proves nothing about the next build. Use tools. -fsanitize=undefined (UBSan) instruments overflow, bad shifts, misaligned access, and more. -fsanitize=address (ASan) catches out-of-bounds and use-after-free on the heap and stack. Valgrind catches uninitialized reads and leaks without recompiling. Turn on -Wall -Wextra and treat the warnings as errors. None of these prove absence, they only find what your test inputs happen to trigger, which is why the habit of writing code with no undefined behavior in the first place is the real defence.
Code Examples
#include <limits.h>
#include <stdio.h>
// BROKEN: signed overflow is undefined, so the compiler may assume
// x + 1 > x always holds and delete this entire check at -O2.
static int adds_overflow_broken(int x) {
return x + 1 < x;
}
// Correct: check the precondition before performing the arithmetic,
// so the overflow never happens and there is nothing to detect.
static int adds_overflow(int x) {
return x == INT_MAX;
}
int main(void) {
printf("broken says %d, correct says %d\n",
adds_overflow_broken(INT_MAX), adds_overflow(INT_MAX));
// At -O0 this often prints "1, 1". At -O2 it commonly prints "0, 1".
// Same source, same compiler, different answer: that is the hallmark of UB.
return 0;
}#include <stdio.h>
struct node {
int value;
struct node *next;
};
// BROKEN: the dereference happens before the null test. The compiler
// infers n is non-null from the dereference and removes the test.
static int value_broken(struct node *n) {
int v = n->value;
if (n == NULL) {
return -1;
}
return v;
}
// Correct: test first, then dereference. The order is the whole fix.
static int value_of(struct node *n) {
if (n == NULL) {
return -1;
}
return n->value;
}
int main(void) {
struct node head = {42, NULL};
printf("%d\n", value_of(&head)); // 42
printf("%d\n", value_of(NULL)); // -1
(void)value_broken; // never call it with NULL
return 0;
}#include <stdint.h>
#include <stdio.h>
#include <string.h>
// _Static_assert is C11. It fails the build instead of failing at runtime.
_Static_assert(sizeof(float) == sizeof(uint32_t), "float is not 32 bits here");
// BROKEN: reading a float object through a uint32_t pointer violates the
// strict aliasing rule (C11 6.5p7) and is undefined.
static uint32_t float_bits_broken(float f) {
return *(uint32_t *)&f;
}
// Correct: memcpy is the portable way to reinterpret an object
// representation. Optimizers recognise this and emit no actual copy.
static uint32_t float_bits(float f) {
uint32_t bits;
memcpy(&bits, &f, sizeof bits);
return bits;
}
int main(void) {
printf("0x%08x\n", float_bits(1.0f)); // 0x3f800000 on IEEE-754 targets
(void)float_bits_broken;
return 0;
}Common Gotchas
"It works on my machine" is not evidence
undefined behavior can stay dormant across an entire test suite and then change the program when you add an unrelated function, bump the optimizer, or switch compilers. A passing run is not a proof of correctness.
Unsigned overflow is defined, signed overflow is not
`unsigned int` arithmetic wraps modulo `2^N` by definition. `int` arithmetic that exceeds `INT_MAX` is undefined. Casting to `unsigned` before the arithmetic is a legitimate way to get wraparound you can rely on.
The damage is not local
undefined behavior in one branch can let the optimizer draw conclusions that change a different branch, or remove a bounds check ten lines away. Do not assume the wrong output appears near the wrong line.
Sanitizers find, they do not prove
UBSan and ASan only report what your inputs exercise, and cannot be combined with every other tool. Run them in CI on your test suite, and still read the code.