*** Welcome to piglix ***

Arithmetic overflow


In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits - either larger than the maximum or lower than the minimum representable value.

The most common result of an overflow is that the least significant representable bits of the result are stored the result is said to wrap around the maximum (i.e. modulo power of two).

An overflow condition gives incorrect results and, particularly if the possibility has not been anticipated, can compromise a program's reliability and security.

On some processors like graphics processing units (GPUs) and digital signal processors (DSPs), the result saturates; that is, once the maximum value is reached, any attempt to increase it always returns the maximum integer value.

The register width of a processor determines the range of values that can be represented. Typical binary register widths for unsigned integers include:

When an arithmetic operation produces a result larger than the maximum above for a N-bit integer, an overflow reduces the result to modulo N-th power of 2, retaining only the least significant bits of the result and effectively causing a wrap around.

In particular, multiplying or adding two integers may result in a value that is unexpectedly small, and subtracting from a small integer may cause a wrap to a large positive value (for example, 8-bit integer addition 255 + 2 results in 1, which is 257 mod 28, and similarly subtraction 0 - 1 results in 255, a two's complement representation of -1).

Such wrap around may cause security problems - if an overflown value is used as the number of bytes to allocate for a buffer, the buffer will be allocated unexpectedly small, leading to a potential buffer overflow and arbitrary code execution.

If the variable has a signed integer type, a program may make the assumption that a variable always contains a positive value. An integer overflow can cause the value to wrap and become negative, which violates the program's assumption and may lead to unexpected behavior (for example, 8-bit integer addition of 127 + 1 results in -128, a two's complement of 128).


...
Wikipedia

...