...
An example of undefined behavior in C99 C is the behavior on signed integer overflow. (See also rule INT32-C. Ensure that operations on signed integers do not result in overflow.) This noncompliant code example depends on this behavior to catch the overflow.
...
This code tests for signed integer overflow by testing to see if a + 100 > a
. This test cannot evaluate to false unless an integer overflow occurs. However, because a conforming implementation is not required to generate code for undefined behavior, and signed integer overflow is undefined behavior, this code may be compiled out. For example, GCC version 4.1.1 optimizes out the assertion for all optimization levels, and GCC and version 4.2.3 optimizes out the assertion for programs compiled with -O2
-level optimization and higher.
On some platforms, the integer overflow will cause causes the program to terminate (before it has an opportunity to test).
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <assert.h> int foo(int a) { assert(a < (INT_MAX - 100)); printf("%d %d\n", a + 100, a); return a; } int main(void) { foo(100); foo(INT_MAX); } |
Risk Assessment
While Although it is rare that the entire application can be strictly conforming, the goal should be that almost all the code is allowed for a strictly conforming program (which among other things means that it avoids undefined behavior), with the implementation-dependent parts confined to modules that the programmer knows he needs to knows are needed to adapt to the platform when it changes.
...
CERT C++ Secure Coding Standard: MSC15-CPP. Do not depend on undefined behavior
ISO/IEC 9899:1999 Section 2011 Section 3.4.3, "undefined Undefined behavior," Section 4, "Conformance," and Annex Seciton J.2, "Undefined behavior"
ISO/IEC TR 24772 "BQF Unspecified Behaviourbehaviour," , "EWF Undefined Behaviourbehaviour," and "FAB Implementation-defined Behaviourbehaviour"
...
Sources
[Seacord 2005] Chapter 5, "Integers"
...