Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: implementation details

...

The following sections examine specific operations that are susceptible to integer overflow. When operating on small integer types (smaller than int), integer promotions are applied. The usual arithmetic conversions may also be applied to (implicitly) convert operands to equivalent types before arithmetic operations are performed. Programmers should understand integer conversion rules before trying to implement secure arithmetic operations. (See INT02-C. Understand integer conversion rules.)

Implementation Details

An example of implementation that GNU GCC invoked with the -fwrapv command-line option defines the same modulo arithmetic for both unsigned and signed integers.

is GNU GCC invoked with the -fwrapvftrapv command-line option . Other implementations may cause causes a hardware trap (also called an exceptional condition) to be generated when a signed integer overflows. On such implementations, a program that causes a signed integer to overflow , which will most likely abnormally exit. On a UNIX system, the result of such an event may be a signal sent to the process. An example of such an implementation is GNU GCC invoked with the -ftrapv command-line option. Still other implementations may

GNU GCC invoked without either the -fwrapv or the -ftrapv option may simply assume that signed integers never overflow and may generate object code accordingly. An example of such an implementation is GNU GCC invoked without either the -fwrapv or the -ftrapv option.

Anchor
Addition
Addition

Addition

...

The C Standard, 6.5.7 paragraph 4 [ISO/IEC 9899:2011], states

...

In almost every case, an attempt to shift by a negative number of bits or by more bits than exist in the operand indicates a bug (logic error). These issues are covered by INT34-C. Do not shift a negative number of bits or more bits than exist in the operand.

Noncompliant Code Example

This noncompliant code example can result in an unrepresentable value. 

...

Compliant Solution

This compliant solution eliminates the possibility of overflow resulting from a left-shift operation:

...