Section 4.15

Signed integer overflow

Definition

Signed integer overflow is the event in which an arithmetic operation on a signed integer type, a type that holds negative as well as positive values, has a true mathematical result outside the range of that type. On current machines a 32-bit int holds the values from −2,147,483,648-2{,}147{,}483{,}648 to 2,147,483,6472{,}147{,}483{,}647. In C, signed overflow is undefined behavior §4.12: the language standard places no requirement on what the program does next, and compilers optimize on the assumption that it never happens.

The idea

A program reads two lengths h and b of type int from a message and has already rejected negative values. To guard against overflow, the programmer tests the sum afterwards: int total = h + b; if (total < h) reject();. The reasoning comes from the processor: a 32-bit adder keeps only the low 32 bits of the true sum, so a sum just above 2,147,483,6472{,}147{,}483{,}647 comes out negative, which is smaller than h.

The compiler reasons from the C standard instead. Because signed overflow is undefined behavior, the compiler may assume that h + b never overflows. Under that assumption h + b < h holds only when b is negative, so the compiler may replace the test by b < 0. The program has already established that b is not negative, so the compiler may then delete the test together with the call to reject. Optimizing C compilers do make deductions of this kind. The check disappears in exactly the case it was written for.

The processor promises a wrapped result; C promises nothing once a signed operation overflows. A C program must therefore never let a signed operation overflow. The test belongs before the operation and may look only at the operands: will h + b fit?

How it works

The range. A signed integer of ww bits in two’s complement, the encoding current processors use, holds the values from m=−2w−1m = -2^{w-1} to M=2w−1−1M = 2^{w-1} - 1. Two’s complement gives the top bit the weight −2w−1-2^{w-1} instead of +2w−1+2^{w-1}, so the range has one more negative value than positive values. For int, the C header <limits.h> names these limits INT_MIN and INT_MAX.

The operations that can overflow are addition, subtraction and multiplication, including x++ and x += y, whenever the true result lies outside the range from mm to MM; negation of mm and division of mm by −1-1, because both would give M+1M + 1; and a left shift whose result does not fit (see the Shift semantics §4.20 entry). Arithmetic on types narrower than int, such as short or int8_t, runs in int, because the integer promotions §4.18 convert such operands to int first (see the Integer promotion and conversion entry).

What the processor does. An add instruction on x86 or Arm keeps the low ww bits of the true sum, which for a sum that does not fit is the true sum minus or plus 2w2^w. In its flag-setting form it also records the signed overflow in the overflow flag §4.42, one of the condition flags. C gives a program no access to that flag.

What C says. C11, the 2011 edition of the ISO standard that defines the C language, states in section 6.5, paragraph 5, that if the result of evaluating an expression is not in the range of representable values for its type, the behavior is undefined. Compiler optimization §3.39 may therefore treat the absence of signed overflow as a fact, for example by simplifying x + 1 > x to true. Unsigned types are the exception: their arithmetic wraps by definition (see the Unsigned modular arithmetic §4.16 entry). C23, the edition published in 2024, requires two’s complement for signed types but leaves signed overflow undefined [309].

Four correct ways to handle a possible overflow.

  1. Test the operands first. For a+ba + b: if b>0b > 0, the sum fits exactly when a≤M−ba \le M - b; if b<0b < 0, exactly when a≥m−ba \ge m - b; if b=0b = 0, always. Neither subtraction can overflow.

  2. Use a checked operation. GCC §12.17 (the GNU Compiler Collection, from the GNU project, whose name stands for GNU’s Not Unix) and the Clang compiler provide __builtin_add_overflow(a, b, &r), which stores the true sum, reduced to the type of r, in r and returns true exactly when the stored value differs from the true sum. C23 offers the same as ckd_add(&r, a, b) in the header <stdckdint.h>, with matching functions for subtraction and multiplication.

  3. Compute in a wider type. Convert an operand, before the operation, to a type that holds every possible result: the sum or product of two 32-bit int values always fits in int64_t.

  4. Change the rules for one compiler. The GCC and Clang compiler option §12.3 -fwrapv defines signed addition, subtraction and multiplication to wrap, and -ftrapv stops the program on overflow. Such code is correct only when built with that option, and a wrapped length is still the wrong length.

During testing, UndefinedBehaviorSanitizer §10.23, a compiler feature that adds run-time checks, reports each signed overflow that actually happens (option -fsanitize=signed-integer-overflow).

Worked example

Take a 32-bit int, so M=2,147,483,647M = 2{,}147{,}483{,}647 and m=−2,147,483,648m = -2{,}147{,}483{,}648, and let a=2,147,483,600a = 2{,}147{,}483{,}600 and b=100b = 100. The true sum is 2,147,483,7002{,}147{,}483{,}700, which exceeds MM by 2,147,483,700−2,147,483,647=532{,}147{,}483{,}700 - 2{,}147{,}483{,}647 = 53. A wrapping adder would return 2,147,483,700−232=2,147,483,700−4,294,967,296=−2,147,483,5962{,}147{,}483{,}700 - 2^{32} = 2{,}147{,}483{,}700 - 4{,}294{,}967{,}296 = -2{,}147{,}483{,}596. That negative value is what the after-the-fact test if (a + b < a) hopes to see, but nothing in C guarantees it.

The operand test runs before any addition. Since b>0b > 0, compute M−b=2,147,483,647−100=2,147,483,547M - b = 2{,}147{,}483{,}647 - 100 = 2{,}147{,}483{,}547, a value that fits. The test asks whether a≤2,147,483,547a \le 2{,}147{,}483{,}547. It is not, because 2,147,483,6002{,}147{,}483{,}600 is larger by 53, so the program rejects the input and never forms the sum. With a=2,147,483,500a = 2{,}147{,}483{,}500 instead, the test passes, and the sum 2,147,483,6002{,}147{,}483{,}600 is at most MM, as the test promised.

For a negative bb, take a=−2,147,483,600a = -2{,}147{,}483{,}600 and b=−100b = -100. Compute m−b=−2,147,483,648+100=−2,147,483,548m - b = -2{,}147{,}483{,}648 + 100 = -2{,}147{,}483{,}548. The test asks whether a≥−2,147,483,548a \ge -2{,}147{,}483{,}548. It is not, so the program rejects the input. The true sum, −2,147,483,700-2{,}147{,}483{,}700, is indeed below mm.

Stated precisely

Let TT be a signed integer type after integer promotion, with least value mm and greatest value MM. For aa and bb of type TT, the expression a + b overflows exactly when the mathematical sum satisfies a+b<ma + b < m or a+b>Ma + b > M, and C11, section 6.5, paragraph 5, makes such an evaluation undefined behavior. The sum fits exactly when {a≤M−bif b>0,a≥m−bif b<0,\begin{cases} a \le M - b & \text{if } b > 0, \\ a \ge m - b & \text{if } b < 0, \end{cases} and always when b=0b = 0. Each threshold is itself representable: if b>0b > 0, then 0≤M−b<M0 \le M - b < M; if b<0b < 0, then m<m−b≤0m < m - b \le 0.

The same reasoning covers the other operations: a−ba - b fits exactly when a≥m+ba \ge m + b for b>0b > 0, and exactly when a≤M+ba \le M + b for b<0b < 0; −a-a overflows exactly when a=ma = m; a/ba / b and a%ba \% b are undefined when b=0b = 0, and overflow exactly when a=ma = m and b=−1b = -1 (C11, section 6.5.5, paragraph 6). For a×ba \times b with both operands positive, the product fits exactly when a≤⌊M/b⌋a \le \lfloor M / b \rfloor, where ⌊x⌋\lfloor x \rfloor means xx rounded down; the other sign combinations need similar division tests. These statements assume two’s complement, which C23 requires; C11 also allowed the sign-and-magnitude and ones’ complement encodings, which no current processor uses.

Limits and common mistakes

A check after the operation often appears to work in a build without optimization and fails only in the optimized build, which makes the mistake easy to miss.

A wider destination does not widen the operation. In int64_t r = a * b; with int operands, the multiplication runs in int and can overflow before the conversion to int64_t. Convert an operand first: (int64_t)a * b.

Unsigned arithmetic never overflows in the C sense: it wraps modulo 2N2^N, where NN is the number of bits. The after-the-fact test r = a + b; if (r < a) is therefore valid for unsigned int and wider unsigned types (see the Unsigned modular arithmetic entry).

Unsigned declarations can hide signed arithmetic. Two uint16_t operands are promoted to int on a machine with a 32-bit int, so 50,000×50,000=2,500,000,00050{,}000 \times 50{,}000 = 2{,}500{,}000{,}000 overflows int, although no variable is signed.

Storing an out-of-range value in a narrow signed type is a conversion, not an overflowing operation. int8_t x = 100 + 100; computes 200 in int without overflow, and converting 200 to int8_t is implementation-defined behavior §4.13 (C11, section 6.3.1.3): each compiler must choose and document the result, and GCC gives 200−256=−56200 - 256 = -56.

The Common Weakness Enumeration (CWE), a public catalog of software weaknesses, lists this class of bug as CWE-190, integer overflow or wraparound.

Questions answered

Why is checking the result after an overflowing addition too late?

Checking the result after an overflowing signed addition is too late because, in C, the overflowing addition is itself undefined behavior: from that point the language places no requirement on the program, so no guaranteed result is left to check. An optimizing compiler may assume that the addition never overflows. Under that assumption a test such as if (a + b < a), with b known to be positive, is always false, and the compiler may delete it. The test disappears in exactly the case it was written to catch.

The test must come before the addition and use only the operands. Let INT_MAX and INT_MIN be the largest and smallest int values. For positive b, add only if a <= INT_MAX - b; for negative b, add only if a >= INT_MIN - b. Neither subtraction can overflow. With a 32-bit int, a=2,147,483,600a = 2{,}147{,}483{,}600 and b=100b = 100 are rejected, because aa exceeds 2,147,483,647−100=2,147,483,5472{,}147{,}483{,}647 - 100 = 2{,}147{,}483{,}547. The alternatives are a checked addition that reports whether the true sum fits (__builtin_add_overflow in GCC and Clang, ckd_add in C23) and an addition in a wider type. For unsigned types an after-the-fact test is valid, because unsigned arithmetic wraps by definition.

Related entries: Undefined behavior (UB) (§4.12), Integer promotion and conversion (§4.18), Unsigned modular arithmetic (§4.16), Overflow-safe range check (§4.17), Implementation-defined behavior (§4.13), UndefinedBehaviorSanitizer (§10.23). Further reading: [26, 78, 309].