Undefined Behavior & Safety

undefined behavior (UB)

Imagine a board game whose rulebook covers what happens for every legal move, but for one specific illegal move it simply says nothing — not 'you lose', not 'roll again', just silence. If a player makes that move, the rulebook gives the referee no guidance at all, so literally anything could follow. That silence is what C calls undefined behavior. It is the most important and most misunderstood idea in the whole language.

Here is the precise meaning, and it is worth reading slowly: undefined behavior is behavior for which the C standard imposes NO requirements. That is the whole definition. It does not mean 'the result is random'. It does not mean 'the result depends on your machine' (that is a different category called implementation-defined). It does not even mean 'the program will crash'. It means the standard washes its hands entirely — a program that triggers undefined behavior has no defined behavior, not for that line, and arguably not for the whole run. A crucial consequence follows: because the standard says a correct program never triggers undefined behavior, the optimizer is PERMITTED TO ASSUME it never happens. It can then build its reasoning on that assumption and produce code that, when the assumption turns out false, does something wildly unrelated to what you wrote.

Why this matters: undefined behavior is not a theoretical curiosity, it is the root cause behind a huge share of real-world crashes and security holes. The classic trap is that a program with undefined behavior may seem to work perfectly — until a new compiler version, a higher optimization level, or a slightly different input makes the assumption visible and the program breaks in a way that has no obvious connection to the original mistake. The honest engineering stance is simple: undefined behavior is always a bug, even when it produces the answer you wanted today.

int a[5]; int x = a[10]; /* out of bounds: undefined behavior */ int *p = 0; int y = *p; /* null dereference: undefined behavior */ int z = INT_MAX + 1;/* signed overflow: undefined behavior */

Three classic triggers. The standard guarantees nothing about what any of these lines does — not even that they crash.

The single most repeated misconception: UB does NOT mean 'random' or 'crashes' or 'platform-dependent'. It means the standard imposes no requirements, so the compiler may ASSUME it never happens — which is exactly what makes silently-working UB so dangerous.

Also called
UB未定義行為UB