Computing Library › Number Systems & Information
Number Systems & Information

Integer Overflow

Overflow happens when an arithmetic result exceeds the range a fixed-width integer can hold.

What goes wrong

A fixed-width integer can only hold values in a set range. When a computation produces a result outside that range, the extra high bits are lost and the stored value is wrong — this is overflow.

Unsigned wraparound

Kronos motion — when

Unsigned overflow is defined as modular arithmetic: results wrap around modulo 2ⁿ. Adding 1 to the maximum 8-bit unsigned value 255 gives 0. This behavior is predictable and sometimes used deliberately.

Signed overflow

Signed overflow occurs when adding two same-sign numbers gives a result of the wrong sign. In some languages, such as C, signed overflow is undefined behavior, which lets compilers make assumptions that can surprise the unwary.

Real consequences

Overflow bugs have caused crashes and security holes. A classic case is a length calculation that overflows to a small value, letting a later copy write past a buffer. Array index and size arithmetic deserve special care.

Prevention

python
def add_checked(a, b, bits=32):
    lo, hi = -(1 << (bits-1)), (1 << (bits-1)) - 1
    r = a + b
    if not (lo <= r <= hi):
        raise OverflowError('signed overflow')
    return r