Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Integer operations must result in an integer value within the range of the integer type (that is, the resulting value is the same as the result produced by unlimited-range integers). Frequently, the range is more restrictive based on the use of the integer value, for example, as an index. Integer values can be verified by code review or by static analysis.

Integer overflow is undefined behavior, so a compiled program can do anything, including going off to play the Game of Life. Furthermore, a compiler may perform optimizations that assume an overflow will never occur, which could easily yield unexpected results. Compilers can optimize away if statements that check if an overflow occured. See MSC15-A. Do not depend on undefined behavior for an example.

Wiki Markup
Verifiably in -range operations are often preferable to treating out -of -range values as an error condition because the handling of these errors has been repeatedly shown to cause denial-of-service problems in actual applications. The quintessential example of this is the failure of the Ariane 5 launcher, which occurred due to an improperly handled conversion error that resulted in the processor being shut down \[[Lions 96|AA. C References#Lions 96]\].

...

Now, if the user types a < b, there is often an implicit subtraction happening. On a machine without condition codes, the compiler may simply issue a subtract instruction and check whether the result is negative. This is allowed, because the compiler is allowed to assume there is no overflow. If all explicitly user-generated values are kept in the range [INT_MIN/2, INT_MAX/2, then comparisons will always work even if the compiler performs this optimization on such hardware.

...

Code Block
bgColor#ccccff
long i = /* Expression that evaluates to the value 32767 */;
/* ... */
/* No test is necessary; i is known not to overflow. */
/* expression involving i + 1 */

Risk Assessment

Out-of-range integer values can result in fetches or stores from arbitrary memory locations and the execution of arbitrary code.

...