...
In modwrap semantics (also called modulo arithmetic), integer values "wrap round." That is, adding 1 to MAX
produces MIN
. This is the defined behavior for unsigned integers in the C Standard [ISO/IEC 9899:2011], Section section 6.2.5, paragraph 9. It 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.
...
Using a long
instead of an int
is guaranteed to accommodate the computed value.:
Code Block | ||||
---|---|---|---|---|
| ||||
long i = /* Expression that evaluates to the value 32767 */; /* ... */ /* No test is necessary; i is known not to overflow. */ /* expression involving i + 1 */ |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
| Could detect violations of this recommendation by flagging any comparison expression involving addition that could potentially overflow. For example, instead of comparing | ||||||
| 488 S | Partially implemented. | |||||||
PRQA QA-C |
| 0272 (I) | Partially implemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...