{
  "id": "integer-overflow",
  "title": "Integer Overflow",
  "lang": "en",
  "source_lang": "en",
  "summary": "Integer overflow occurs when an integer operation produces a mathematical result outside the range representable by its result type.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "Integral overflow",
    "Integer arithmetic overflow"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/integer-overflow/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/integer-overflow/",
      "json": "https://aiwiki.page/zh/integer-overflow.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Integer overflow occurs when the mathematical result of an operation on integers lies outside the range representable by the operation’s result type. It arises primarily in computing systems that represent integers using a fixed number of bits. Depending on the hardware, programming language, operation, and execution settings, overflow may produce a wrapped value, raise an exception, clamp the result to a boundary, or invoke behavior for which the language imposes no requirements. Overflow can be intentional, as in some cryptographic calculations, or erroneous, causing incorrect results and potentially creating security vulnerabilities."
    },
    {
      "heading": "Representation and range",
      "text": "A fixed-width integer type can represent only a finite set of values. An unsigned integer with \\(n\\) bits normally represents the range\n\n\\[0 \\leq x \\leq 2^n-1.\\]\n\nA signed integer using two’s-complement representation represents\n\n\\[-2^{n-1} \\leq x \\leq 2^{n-1}-1.\\]\n\nFor example, an unsigned 8-bit integer ranges from 0 to 255, while a signed 8-bit two’s-complement integer ranges from −128 to 127. The mathematical sum \\(250+10=260\\) cannot be represented in the unsigned type; similarly, \\(127+1=128\\) cannot be represented in the signed type.\n\nThe range is asymmetric for signed two’s-complement integers: there is one more negative value than positive value. Consequently, negating the minimum representable value overflows if the result must remain in the same signed type. Taking its absolute value has the same representability problem.\n\nOverflow is not limited to addition. Subtraction, multiplication, exponentiation, and some shift operations can exceed representable ranges. Signed division also has a boundary case: dividing the minimum two’s-complement integer by \\(-1\\) produces a positive result that cannot fit in the same type. Division by zero is a separate error, not integer overflow.\n\nOverflow, underflow, and conversion\n\nA result below an integer type’s minimum is sometimes called integer underflow. For example, unsigned subtraction \\(0-1\\) falls below the unsigned range. Many technical discussions use integer overflow for violations of either bound.\n\nThis differs from floating-point underflow, which concerns values close to zero and the limits of floating-point representation. Floating-point overflow and underflow follow different rules, often those of IEEE 754.\n\nConverting a value into a narrower integer type can also lose information. Strictly speaking, this is an out-of-range conversion rather than arithmetic overflow, although both are commonly grouped under integer-related errors. A calculation may succeed in a wide type and become incorrect only when assigned to a narrower destination."
    },
    {
      "heading": "Responses to overflow",
      "text": "Several arithmetic models are used in hardware and software.\n\nWrapping arithmetic\n\nWrapping arithmetic reduces the result modulo \\(2^n\\):\n\n\\[r=(a+b)\\bmod 2^n.\\]\n\nThis is an application of modular arithmetic. For unsigned 8-bit values, \\(250+10\\) therefore produces 4.\n\nWhen a wrapped bit pattern is interpreted as a signed two’s-complement integer, it may change sign. Under an explicitly wrapping signed 8-bit model, \\(127+1\\) becomes \\(-128\\). This behavior is common at the machine-instruction level, but it must not be assumed for every programming language.\n\nWrapping arithmetic is useful when modular behavior is part of an algorithm’s specification. It appears in cryptographic hash functions, checksums, pseudorandom number generators, and cyclic counters. In such contexts, wraparound may be the intended result rather than a defect.\n\nChecked arithmetic\n\nChecked arithmetic detects an out-of-range result and reports failure. The reporting mechanism may be an exception, a trap, an error return, or a separate overflow flag.\n\nDetection alone does not determine how a program should recover. Depending on the application, a failed operation may lead to rejecting input, abandoning a calculation, or switching to a wider representation.\n\nSaturating arithmetic\n\nSaturating arithmetic replaces an out-of-range result with the nearest representable boundary:\n\n\\[\\operatorname{sat}(x)= \\begin{cases} L & x<L,\\\\ x & L\\leq x\\leq U,\\\\ U & x>U, \\end{cases}\\]\n\nwhere \\(L\\) and \\(U\\) are the type’s minimum and maximum values.\n\nFor an unsigned 8-bit type, a saturating addition of 250 and 10 produces 255. Saturation is useful in image processing and signal processing, where a large positive quantity turning into a small or negative quantity would often be undesirable. It nevertheless changes the mathematical result and is not interchangeable with checked arithmetic.\n\nArbitrary-precision arithmetic\n\nArbitrary-precision arithmetic expands the representation as values grow, rather than imposing a fixed numeric range. Its practical limits are available memory, execution time, and implementation constraints.\n\nIt avoids ordinary fixed-width overflow, but it does not guarantee that an entire program is free of range errors. Converting a large integer to a fixed-width field, passing it to a native library, or using it as an allocation size can still introduce limits."
    },
    {
      "heading": "Hardware behavior",
      "text": "A central processing unit generally performs integer arithmetic using fixed-width registers. An addition instruction may retain only the low-order bits while recording additional information in status flags.\n\nTwo flags often distinguished are:\n\n- Carry, which indicates a carry beyond the unsigned result width during addition.\n- Signed overflow, which indicates that the result is outside the signed representable range.\n\nThese are different conditions. In 8-bit addition, \\(255+1\\) produces a carry, but the corresponding signed operation \\(-1+1\\) does not overflow. Conversely, \\(127+1\\) overflows as a signed operation but produces no carry beyond the eighth bit.\n\nFor two’s-complement addition, signed overflow occurs when operands with the same sign produce a stored result with the opposite sign. For subtraction, it occurs when operands have different signs and the stored result’s sign differs from that of the first operand.\n\nNot every instruction set architecture exposes the same flags or instructions. Some provide trapping operations or special saturating instructions. Hardware behavior and source-language behavior must therefore be considered separately: a compiler is governed by the language’s rules, not merely by the apparent behavior of a particular processor instruction."
    },
    {
      "heading": "Programming-language semantics",
      "text": "Languages differ substantially in their treatment of overflow, and some offer several arithmetic modes.\n\nC and C++\n\nIn C and C++, unsigned arithmetic is defined modulo one greater than the maximum representable value of the unsigned result type. Signed arithmetic overflow generally has undefined behavior: the language imposes no requirements on an execution that performs it.\n\nThe distinction affects optimization. For a signed integer x, a compiler may simplify x + 1 > x to true because the only ordinary case that would invalidate the comparison involves signed overflow, which is not permitted in a defined execution. A program cannot reliably use such an expression to detect signed overflow after it occurs.\n\nInteger promotions also matter. Operations on small integer types may first be performed in int, so an apparent 8-bit operation may actually be a wider calculation followed by a narrowing conversion. The operand declarations alone do not always establish the arithmetic width.\n\nC23 introduced checked integer arithmetic facilities through <stdckdint.h>, including ckd_add, ckd_sub, and ckd_mul. Compilers also commonly provide overflow-detection built-ins.\n\nOther language models\n\n- Java: Ordinary arithmetic on int and long uses fixed-width results with defined wraparound for addition, subtraction, and multiplication. Methods such as Math.addExact provide checked alternatives.\n- Rust: Ordinary integer operations are subject to configurable overflow checks; checks are normally enabled in development profiles and disabled in release profiles. Explicit checked, wrapping, saturating, and overflowing methods make the intended behavior independent of that default.\n- Python: Built-in integers use arbitrary precision, so ordinary integer arithmetic is not limited to a fixed machine width. Fixed-width external interfaces and numerical-array libraries may behave differently.\n- C#: Integral operations can be evaluated in checked or unchecked contexts. Overflow handling depends on the context, compiler settings, and whether an expression is evaluated at compile time.\n\nJavaScript requires a further distinction. Its ordinary Number values use binary floating-point representation, so loss of exactness for sufficiently large integers is not ordinary fixed-width integer wraparound. BigInt supports arbitrary-precision integers, while bitwise operations and fixed-width storage formats have their own conversion and width rules."
    },
    {
      "heading": "Consequences for correctness and security",
      "text": "Integer overflow can corrupt counters, timestamps, financial calculations, array indices, and termination conditions. A counter that wraps unexpectedly may cause a loop to continue longer than intended or never reach a stopping value.\n\nA classic algorithmic example is computing the midpoint of two nonnegative indices:\n\nmid = (low + high) / 2\n\nThe sum can overflow even when both indices are valid. Under suitable integer and ordering assumptions, the equivalent expression\n\nmid = low + (high - low) / 2\n\navoids that intermediate overflow. This issue is relevant to binary search and related algorithms. The assumptions matter: the alternative is not universally safe for arbitrary signed endpoints.\n\nIn cybersecurity, overflow can become a security vulnerability when an incorrect value crosses a trust or memory-safety boundary. For example, a program might calculate an allocation size as\n\n\\[\\text{bytes}=\\text{count}\\times\\text{element size}.\\]\n\nIf the multiplication wraps to a small value, the program may allocate less memory than intended. Subsequent writes based on the original count can then cause a buffer overflow.\n\nOther consequences include bypassed bounds checks, incorrect resource limits, and denial of service. Signed–unsigned conversions can compound these problems: a negative value converted to an unsigned type may become a very large positive value.\n\nInteger overflow and buffer overflow are distinct. The former is an arithmetic representability problem; the latter is an access beyond a memory buffer. Either can occur without the other."
    },
    {
      "heading": "Detection and prevention",
      "text": "Avoiding unintended overflow requires choosing arithmetic semantics that match the application and checking intermediate operations, not only final results.\n\nFor unsigned addition with maximum value \\(U\\), the sum of representable nonnegative values \\(a\\) and \\(b\\) is in range exactly when\n\n\\[a\\leq U-b.\\]\n\nFor unsigned multiplication with \\(b>0\\), the corresponding condition is\n\n\\[a\\leq \\left\\lfloor\\frac{U}{b}\\right\\rfloor.\\]\n\nThese preconditions avoid calculating the potentially overflowing result. Signed checks require additional cases because operands can have different signs and the negative range is asymmetric. Checked-arithmetic primitives can express the requirement directly without reproducing those cases manually.\n\nUsing a wider intermediate type can help, but widening must occur before the operation. Assigning a narrow multiplication’s result to a wider destination does not repair overflow that already occurred. The wider type also needs a justified range bound.\n\nCommon verification techniques include:\n\n- Boundary tests around minimum and maximum values, zero, and sign changes.\n- Static analysis to identify potentially overflowing expressions and unsafe conversions.\n- Runtime instrumentation that reports selected arithmetic violations during execution.\n- Fuzz testing to explore unusual combinations of inputs and control flow.\n- Formal verification using explicit arithmetic models and bounds on intermediate values.\n\nTesting with runtime checks cannot prove that all paths are safe, while static tools may report cases that cannot actually occur. Formal reasoning must distinguish mathematical integers from fixed-width machine integers; proving an algorithm correct over unbounded integers does not by itself establish that its implementation is free of overflow."
    }
  ],
  "links": [
    "bit",
    "programming-language",
    "twos-complement",
    "ieee-seven-five-four",
    "modular-arithmetic",
    "algorithm",
    "cryptographic-hash-function",
    "image-processing",
    "central-processing-unit",
    "compiler",
    "c-programming-language",
    "javascript",
    "binary-search",
    "cybersecurity",
    "security-vulnerability",
    "denial-of-service-attack",
    "formal-verification"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}