
...
This compliant solution uses the addExact()
and multiplyExact()
methods defined in the Math
class. These methods were added to Java as part of the Java 8 release, and they also either return a mathematically correct value or throw ArithmeticException
. The Math
class also provides SubtractExactprovides subtractExact()
and negateExact()
but does not provide any methods for safe division or absolute value.
...
Failure to perform appropriate range checking can lead to integer overflows, which can cause unexpected program control flow or unanticipated program behavior.
Rule | Severity | Likelihood | Detectable | Remediation CostRepairable | Priority | Level |
---|---|---|---|---|---|---|
NUM00-J | Medium | Unlikely | No | MediumNo | P4P2 | L3 |
Automated Detection
Automated detection of integer operations that can potentially overflow is straightforward. Automatic determination of which potential overflows are true errors and which are intended by the programmer is infeasible. Heuristic warnings might be helpful.
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.MATH.ABSRAND | Abs on random (Java) | ||||||
Coverity | 7.5 | BAD_SHIFT | Implemented | ||||||
Klocwork |
| SV.INT_OVF | |||||||
Parasoft Jtest |
| CERT.NUM00.ICO CERT.NUM00.BSA CERT.NUM00.CACO | Avoid calculations which result in overflow or NaN Do not use an integer outside the range of [0, 31] as the amount of a shift Avoid using compound assignment operators in cases which may cause overflow | ||||||
PVS-Studio |
| V5308, V6117, V6130, V6131 |
Related Guidelines
INT32-C. Ensure that operations on signed integers do not result in overflow | |
ISO/IEC TR 24772:2010 | Wrap-around Error [XYY] |
CWE-682, Incorrect Calculation |
...