Integer overflow

On this page 7

An integer overflow is a software flaw in which an arithmetic operation produces a result outside the range that a fixed-width integer type can represent, so the stored value wraps around, is truncated or becomes undefined. In cybersecurity, integer overflows belong to the class of memory safety and logic vulnerabilities, cataloged as CWE-190 (and CWE-191 for integer underflow), and they are dangerous mainly because the wrong number is later used to size a buffer, index an array or check a limit.

The overflow itself rarely causes harm. The harm appears one step later, when a small, wrapped value convinces the program that a large input fits into a small allocation, which often leads to a heap buffer overflow and, in the worst case, remote code execution.

How integer overflow happens

Computers store integers in a fixed number of bits, typically 8, 16, 32 or 64. An unsigned 32-bit integer holds values from 0 to 4,294,967,295; adding 1 to the maximum yields 0 because the carry bit is discarded. This behavior is modular arithmetic modulo 2 to the power of the bit width.

Signed integers use two’s complement representation, so exceeding the maximum positive value flips the sign bit and produces a large negative number. In C and C++, signed overflow is undefined behavior: the compiler may assume it never happens and remove safety checks that depend on it, which turns an apparently harmless bug into an exploitable one.

The following table lists the ranges that matter most when reviewing code for overflow risk.

TypeMinimum valueMaximum value
uint80255
int16-32,76832,767
uint16065,535
int32-2,147,483,6482,147,483,647
uint3204,294,967,295
int64about -9.22 quintillionabout 9.22 quintillion
Ranges of common integer types

Variants of integer errors

Integer overflow is the best-known member of a family of numeric errors that share one root cause: a value that does not fit the type that holds it. Security reviewers treat them together because they produce the same downstream symptoms and require the same defensive discipline.

VariantWhat happensTypical consequence
Unsigned wraparoundValue exceeds maximum and restarts at zeroUndersized allocation, short copy length check
Signed overflowPositive value becomes negative or vice versaUndefined behavior, removed bounds checks
Integer underflowSubtraction goes below the minimumHuge length value, out-of-bounds read
TruncationWide value is stored in a narrower typeHigh bits lost, length mismatch
Sign conversion errorNegative signed value is cast to unsignedSmall negative becomes a very large size
Multiplication overflowCount times element size exceeds rangeAllocation far smaller than the data written
Integer error variants and their typical effects

The multiplication pattern is especially common in allocation code: an attacker supplies an element count so large that count * size wraps to a small number. The program allocates a few bytes and then writes the full attacker-controlled data, corrupting the heap.

Why integer overflow becomes a security vulnerability

An integer overflow becomes exploitable when the corrupted value flows into a security-relevant decision. Typical sinks are memory allocation sizes, buffer offsets, loop bounds, length checks and resource limits. Because attackers often control the input numbers, for example a length field in a file header or network packet, they can choose values that wrap precisely to the size they need.

The table compares integer overflow with closely related vulnerability classes, which helps when classifying findings with CWE identifiers or scoring them with CVSS.

Vulnerability classRoot causeRelationship to integer overflow
Integer overflowArithmetic exceeds type rangeThe initial numeric error
Buffer overflowWrite beyond allocated memoryFrequent consequence of a wrapped size
Use-after-freeAccess to released memoryCan follow from a wrapped reference count
Out-of-bounds readRead beyond valid dataOften caused by an underflowed length
Denial of serviceResource exhaustion or crashResult of an overflowed loop or limit
Integer overflow compared with related vulnerability classes

Reference count overflows illustrate a subtler path. If a 32-bit counter of object references wraps to zero, the object is freed while still in use, producing a use-after-free condition that kernel exploit developers have repeatedly targeted.

Prevention and detection

Preventing integer overflow requires checking arithmetic before the result is used, not after. Checking whether a + b is smaller than a works for unsigned types but fails for signed types in C, because the overflow itself is undefined. Safe code validates operands against limits first or uses checked arithmetic primitives.

Language choice changes the default risk considerably. The decision table summarizes practical defenses by environment.

EnvironmentRecommended defenseReason
C and C++Compiler builtins such as __builtin_add_overflow, safe integer librariesDetects overflow without undefined behavior
Rustchecked_add, saturating_add, overflow checks in release buildsDebug panics alone do not protect production
Java and C#Math.addExact or the checked contextDefault arithmetic wraps silently
PythonValidate sizes passed to native extensionsNative integers are unbounded, but C libraries are not
Smart contractsCompiler-level checked arithmeticOverflow can mint or drain tokens
Defenses against integer overflow by environment
  • Use size-appropriate types such as size_t for lengths and avoid mixing signed and unsigned operands.
  • Validate untrusted lengths against realistic maximums before any arithmetic.
  • Enable sanitizers such as UndefinedBehaviorSanitizer and flags like -ftrapv during testing.
  • Fuzz parsers with extreme numeric values, because coverage-guided fuzzing finds wraparound quickly.
  • Use static analysis to flag unchecked multiplications in allocation calls.

Common misconceptions about integer overflow

Several widespread assumptions lead developers to underestimate integer overflow. The most dangerous one is that 64-bit types eliminate the problem. Larger types raise the threshold, but attacker-controlled values can still reach it, and truncation to 32-bit fields in file formats or protocols reintroduces the risk.

  • Memory-safe languages are not fully immune: they prevent memory corruption, yet a wrapped value can still break business logic, such as a negative price or a bypassed quota.
  • A post-operation check is not always valid: compilers may delete checks that rely on signed overflow in C and C++.
  • Small values are not automatically safe: underflow from subtracting a header size can produce an enormous length.
  • Compiler warnings do not catch everything: most overflow depends on runtime input and needs dynamic testing.

A plain-language summary

A computer stores each number in a box of fixed size. If a calculation produces a number too big for its box, the extra part is simply lost. The number wraps around, much like a car odometer rolling from 999,999 back to zero.

That alone sounds harmless. The trouble starts when the program uses the wrong number to decide how much space to reserve. It reserves a tiny space and then pours in a huge amount of data. The data spills over into memory it should never touch, and an attacker may use that spill to take control of the program.

An example from practice

A security researcher fuzzes an image decoding library used by a desktop photo viewer. The image header stores width and height as 32-bit unsigned values, and the decoder computes the buffer size as width times height times 4 bytes per pixel. A crafted file declares a width of 65,536 and a height of 16,385, so the product wraps and the program allocates only 262,144 bytes instead of more than 4 GB.

The decoder then writes pixel rows into that small buffer, overrunning the heap. The researcher demonstrates controlled memory corruption and reports the flaw through coordinated vulnerability disclosure. The vendor assigns a CVE, rates it high severity under CVSS and ships a fix that uses checked multiplication and rejects images larger than a defined pixel limit.

The outcome is a patched library before public exploitation, plus a new fuzzing target in the vendor’s continuous integration pipeline that catches similar wraparound bugs in later releases.