Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Linked to UB #33 and examples of implementation details.

Integer 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.

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.

Other implementations may cause a hardware trap (also referred to as an exceptional condition) to be generated when a signed integer overflows. On such implementations a program that causes a signed integer to overflow 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.

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

that defines signed integer types as being modulo, for example, need not detect integer overflow. Implementations may also trap on signed arithmetic overflows, or simply assume that overflows will never happen and generate object code accordingly. (See recommendation MSC15-C. Do not depend on undefined behavior.) For these reasons, it is important to ensure that operations on signed integers do no result in signed overflow. (See recommendation MSC15-C. Do not depend on undefined behavior.) Of particular importance, however, are operations on signed integer values that originate from untrusted sources and are used in any of the following ways:

...