...
Wiki Markup |
---|
In modwrap semantics (also called _modulo_ arithmetic), integer values "wrap round". That is, adding one to {{MAX}} produces {{MIN}}. This is the defined behavior for unsigned integers in the C Standard \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] (see Section 6.2.5, "Types", paragraph 9) and is frequently the behavior of signed integers as well. However, it is more sensible in many applications to use saturation semantics instead of modwrap semantics. For example, in the computation of a size (using unsigned integers), it is often better for the size to stay at the maximum value in the event of overflow, rather than suddenly becoming a very small value. |
Restricted Range Usage
Wiki Markup |
---|
Another tool for avoiding integer overflow is to use only half the range of signed integers. For example, when using an {{int}}, use only the range \[{{INT_MIN}}/2, {{INT_MAX}}/2\]. This has been a trick of the trade in Fortran for some time, and now that optimizing C compilers are becoming more sophisticated, it can be valuable in C. |
Non-Compliant Code Example
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, and compilers can take advantage of this to produce faster code by assuming an overflow will not happen. Therefore, the if
statement that is intended to catch an overflow might be optimized away.
Code Block | ||
---|---|---|
| ||
int i = /* some expression that evaluates to the value 32767 */;
/* ... */
if (i + 1 < i) {
/* handle overflow */
}
|
Compliant Solution
Using a long
instead of an int
is guaranteed to accommodate the computed value.
Code Block | ||
---|---|---|
| ||
long i = /* some expression that evaluates to the value 32767 */;
/* ... */
/* No test is necessary; i is known not to overflow. */
|
Risk Assessment
If an integer overflow produces an unexpected value which is then used to index into an array, a buffer overflow could result.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT08-A | 2 (medium) | 2 (probable) | 1 (high) | P4 | L3 |
...