Versions Compared

Key

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

...

In the following non-compliant example, i + 1 will overflow on a 16-bit machine.  The C standard allows signed integers to overflow and produce incorrect results. Compilers can take advantage of this to produce faster code by assuming an overflow will not happenoccur.  As a result, the if statement that is intended to catch an overflow might be optimized away.

Code Block
bgColor#ffcccc
int i = /* some expression that evaluates to the value 32767 */;
/* ... */
if (i + 1 <= i) {
  /* handle overflow */
}
/* expression involving i + 1 */

Compliant Solution

Using a long instead of an int is guaranteed to accommodate the computed value.

Code Block
bgColor#ccccff
long i = /* some 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.

...