Section 4.12

Undefined behavior (UB)

Definition

Undefined behavior (UB) is the C standard’s name for what happens when a program breaks some rules of the language, such as overflowing a signed integer, reading outside an array §14.5, or using memory after it has been freed: the standard imposes no requirements. Any outcome conforms, including a crash, a wrong result, a deleted check, or output that looks correct. Compilers may therefore assume that undefined behavior never happens, and optimize on that assumption. Implementation-defined behavior §4.13 is instead a documented choice, and unspecified behavior §4.14 a choice among allowed options.

The idea

A programmer wants to catch the moment a counter of type int, a signed integer of 32 bits on common machines, passes its largest value, 2,147,483,647. The processor’s add instruction wraps around: adding 1 to the largest value gives the most negative value, −2,147,483,648-2{,}147{,}483{,}648. So the programmer writes the test x + 1 < x and expects it to be true exactly when x holds the largest value. With optimization turned on, the widely used C compilers GCC §12.17 (GNU Compiler Collection; GNU stands for GNU’s Not Unix) and Clang delete the test: the program behaves as if it could never be true.

The compiler is not reading the processor’s manual; it is reading the C standard, and in C, overflowing a signed integer is undefined behavior. Think of the standard as a contract between the programmer and the compiler. The programmer promises never to execute an operation whose behavior is undefined. The compiler promises that every program that keeps the promise behaves as the standard describes. Within that contract, x+1x + 1 is always one more than xx, so x+1<xx + 1 < x is always false, and a test that is always false can be removed. The test was meant to catch an execution that, by the contract, does not exist. The picture of a contract stops being accurate in one respect: nobody checks the programmer’s side. A broken promise produces no error message; it produces whatever code the compiler’s reasoning yields.

Undefined behavior exists for two reasons. When C was standardized, machines differed: some encoded negative numbers in other ways than today’s two’s complement, the encoding in which the highest bit of a ww-bit integer counts as −2w−1-2^{w-1}, and some stopped the program on an overflow. Leaving the result undefined let each machine use its fastest instruction. Today the main reason is speed: a compiler that may assume no signed overflow §4.15 can, for example, treat a loop counter as never wrapping around, compute the number of loop iterations in advance, and choose faster instructions for the loop.

How it works

Annex J.2 of the C standard lists the undefined cases. The ones met most often are:

An optimizing compiler uses undefined behavior in three steps.

  1. It assumes that the program never executes an undefined operation. For x + 1, with x of type int, that means x is less than the largest int whenever the addition runs.

  2. It derives facts that hold in every execution without undefined behavior: here, x+1>xx + 1 > x.

  3. It simplifies the code with those facts: x + 1 < x becomes 0, the code that the test guards becomes dead code, code that can never run, and that code is deleted.

Each step is correct for every execution that the standard defines. The standard allows any transformation that keeps the observable behavior, meaning the input and output and the accesses to volatile objects, of every execution without undefined behavior; this is often called the as-if rule. Executions with undefined behavior constrain nothing.

The same reasoning removes other checks that come too late. If a function first reads the field len through a pointer p and only then tests whether p is a null pointer, the compiler may conclude that p cannot be null, because reading through a null pointer would already have been undefined, and delete the test. A 2009 vulnerability in the Linux kernel, CVE-2009-1897 in the CVE (Common Vulnerabilities and Exposures) list, arose this way: GCC removed a null-pointer test that came after the pointer had been used.

Three ways keep a check meaningful.

To find undefined behavior during testing, UndefinedBehaviorSanitizer §10.23, a checking mode of GCC and Clang turned on with -fsanitize=undefined, reports many kinds of undefined operation at the moment they execute.

Worked example

Take a 32-bit int, so the largest int is 231−1=2,147,483,6472^{31} - 1 = 2{,}147{,}483{,}647, and this function:

int will_overflow(int x) { return x + 1 < x; }

Compiled for x86-64 by Clang 23 without optimization (option -O0), the function performs the addition with the processor’s add instruction. For x=2,147,483,647x = 2{,}147{,}483{,}647 that instruction produces the bit pattern 0x80000000, which as an int is −2,147,483,648-2{,}147{,}483{,}648. Since −2,147,483,648<2,147,483,647-2{,}147{,}483{,}648 < 2{,}147{,}483{,}647, the function returns 1. With optimization (option -O2), Clang compiles the whole function to two instructions, one that sets the result to 0 and one that returns, so the function returns 0 for every xx. GCC 13 returns 0 even without optimization, because it simplifies the comparison while it translates the source. Every one of these results is permitted: the call with the largest value has undefined behavior, so no answer is wrong.

A correct test compares before adding: x == INT_MAX. For a general sum a + b with a=2,000,000,000a = 2{,}000{,}000{,}000 and b=200,000,000b = 200{,}000{,}000, the test a > INT_MAX - b first computes 2,147,483,647−200,000,000=1,947,483,6472{,}147{,}483{,}647 - 200{,}000{,}000 = 1{,}947{,}483{,}647, which cannot overflow because bb is positive. Since aa is larger, the test reports the overflow before it happens; the true sum, 2,200,000,000, would indeed exceed the largest int. The Signed integer overflow entry gives the complete test for both signs.

Stated precisely

Clause 3.4.3 of C11, the 2011 edition of the C standard, defines undefined behavior as “behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements”. A note lists the range of possible outcomes: ignoring the situation with unpredictable results, behaving in a documented way characteristic of the environment, or stopping the translation or the execution with a message. The standard’s own example is integer overflow.

Clause 5.1.2.3 states what a compiled program must preserve: its observable behavior, which consists of the accesses to volatile objects, the data written to files by the time the program ends, and the input and output of interactive devices. Call an execution of the source program defined if it performs no undefined operation. A compiler is correct if, for every input whose execution is defined, the compiled program shows an observable behavior that the source program allows for that input. For an execution that performs an undefined operation, the standard imposes no requirement on the result of that operation or on anything that follows it.

In the example, the comparison x+1<xx + 1 < x is evaluated only after x+1x + 1. In every defined execution x≤231−2x \le 2^{31} - 2 when the addition runs, so x+1>xx + 1 > x and the comparison yields 0. Replacing the comparison with 0 therefore preserves every defined execution, which is all the standard asks. The deletion depends on three facts: x has a signed type, since unsigned arithmetic wraps around by definition; no option such as -fwrapv defines the overflow; and the compiler chooses to apply the simplification, which the standard permits but does not require.

Limits and common mistakes

Undefined does not mean that something visibly goes wrong. Undefined behavior often produces the result the programmer expected, until a new compiler version, another optimization level or a change elsewhere in the program changes the generated code. A test that passes shows how one build behaved on one input. It does not show that the program is free of undefined behavior.

The processor’s behavior is not the language’s behavior. The add instruction of almost every processor wraps around, but the compiler reasons with the C rules before it chooses instructions. Knowing what the hardware does is no defense.

Unsigned arithmetic is not undefined. Arithmetic on an unsigned type of NN bits is defined to wrap around modulo 2N2^N, so u + 1 < u for an unsigned int u is a valid test. A wrapped result can still be a logic error; the Unsigned modular arithmetic §4.16 entry treats this.

Sanitizers §10.21 and tests see only what runs. UndefinedBehaviorSanitizer reports an undefined operation only on a path that executes, and it does not detect every kind: use of freed memory, for example, needs AddressSanitizer §10.22.

A compiler option §12.3 is not the language. Code that is correct only with -fwrapv, or with -fno-strict-aliasing, is correct only for compilers that accept that option and only when it is given. Record the dependence and enforce the option in the build.

Undefined behavior is a C and C++ notion. Other languages make other promises. Java defines integer overflow to wrap around. Rust promises that code outside its unsafe blocks cannot cause undefined behavior, provided the unsafe code it relies on is correct; by default a Rust integer overflow panics, which ends the running thread, in a debug build, and wraps around in a release build.

Questions answered

Why can a signed-overflow check disappear after optimization?

A signed-overflow check written as a test on the result, such as x + 1 < x, can disappear because in C signed integer overflow is undefined behavior, and the compiler may assume that undefined behavior never happens. Under that assumption x+1x + 1 is always exactly one more than xx, so x+1<xx + 1 < x is always false, and the optimizer replaces the test with false and deletes the code the test guards. The test could only be true in an execution that has already performed the overflow, and for such an execution the C standard imposes no requirements at all. GCC (the GNU Compiler Collection) and Clang do this when optimizing, for example with -O2.

The repair is to test before the operation, with values that cannot overflow: x == INT_MAX, where INT_MAX is the largest int, or a > INT_MAX - b before computing a + b with a positive b. Alternatives are a checked operation, such as __builtin_add_overflow in GCC and Clang or ckd_add in C23, or arithmetic in an unsigned type, whose wrap-around is defined.

Related entries: Signed integer overflow (§4.15), Shift semantics (§4.20), Compiler optimization (§3.39), Undefined versus unsupported semantics (§3.35), UndefinedBehaviorSanitizer (§10.23), Implementation-defined behavior (§4.13), Unspecified behavior (§4.14). Further reading: [26, 78, 309].