Versions Compared

Key

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

Signed integer overflow is undefined behavior (see undefined behavior 33 in Annex J.2 of C99). This means that implementations have a great deal of latitude in how they deal with signed integer overflow.

Note that according to the C Standard [ISO/IEC 9899:2011], the behavior of arithmetic on atomic signed integer types is defined to use two's complement representation with silent wrap-around on overflow; there are no technically undefined results. However, while defined, these results are unexpected and thus carry similar risks.

An implementation may define the same modulo arithmetic for both unsigned as well as signed integers. On such an implementation, signed integers overflow by wrapping around to zero. An example of such an implementation is GNU GCC invoked with the -fwrapv command line option.

...

This solution is also compliant with rule INT34-C. Do not shift a negative number of bits or more bits than exist in the operand.

Atomic Integers

Note that according to the C Standard [ISO/IEC 9899:2011], the behavior of arithmetic on atomic signed integer types is defined to use two's complement representation with silent wrap-around on overflow; there are no technically undefined results. However, while defined, these results are still unexpected and thus carry similar risks, and have similar solutions to non-atomic integers.

Noncompliant Code Example

This noncompliant code example using atomic integers can result in unexpected signed integer overflow.

Code Block
bgColor#FFcccc
langc
atomic_int i;
int si1;

/* Initialize i, si1 */

atomic_fetch_add(i, si1);

Compliant Solution

This compliant solution tests the operands to guarantee there is no possibility of signed overflow, regardless of representation.

Code Block
bgColor#ccccff
langc
atomic_int i;
int si1;

/* Initialize si1, i */

int si2 = atomic_load(&i);

if (((si2>0) && (si1 > (INT_MAX-si2)))
 || ((si2<0) && (si1 < (INT_MIN-si2)))) {
   /* handle error condition */
}
else {
  atomic_fetch_add(i, si1);
}

Risk Assessment

Integer overflow can lead to buffer overflows and the execution of arbitrary code by an attacker.

...