...
The result has the same sign as the dividend (the first operand in the expression).
Noncompliant Code Example
In this noncompliant code example, the integer hashKey
references an element of the hash
array. However, as the hash key is not guaranteed to be positive, the lookup function may fail, triggering a java.lang.ArrayIndexOutOfBoundsException
on all negative inputs.
Code Block | ||
---|---|---|
| ||
private int SIZE = 16; public int[] hash = new int[SIZE]; public int lookup(int hashKey) { return hash[hashKey % SIZE]; } |
Compliant Solution
This compliant solution calls a method that returns a modulus that is always positive.
Code Block | ||
---|---|---|
| ||
// method imod() gives non-negative result private int SIZE = 16; public int[] hash = new int[SIZE]; private int imod(int i, int j) { return (i < 0) ? ((-i) % j) : (i % j); } public int lookup(int hashKey) { return hash[imod(hashKey, size)]; } |
Compliant Solution
Alternatively, an explicit range check must be performed on the numerator at every susceptible point as demonstrated in this compliant solution.
...
Note that providing a well documented imod
method is a better choice as it improves readability and makes it clear that its sole purpose is to return positive values when required and not to "fix" the unintuitive behavior of the remainder operator, as defined by the specification.
Risk Assessment
Assuming a positive remainder when using the remainder operator can result in incorrect computations.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT02-J | low | unlikely | high | P1 | L3 |
Other Languages
This rule appears in the C Secure Coding Standard as INT10-C. Do not assume a positive remainder when using the % operator.
This rule appears in the C++ Secure Coding Standard as INT10-CPP. Do not assume a positive remainder when using the % operator,
References
Wiki Markup |
---|
\[[JLS 05|AA. Java References#JLS 05]\] [§15.17.3 Remainder Operators|http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3] |