Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The result has the same sign as the dividend (the first operand in the expression).

Noncompliant Code Example

In this noncompliant example, the integer hash references an element of the hash table. However, since hash is not guaranteed to be positive, the lookup function may fail, producing a java.lang.ArrayIndexOutOfBoundsException on all negative inputs.

Code Block
bgColorFFCCCC
private int size=16;
	
public int[] hashTable=new int[size];
	
public int lookup(int hash)
{
  return hashTable[hash % size];
}

Compliant Solution

A compliant solution can call a function that returns a true (always positive) modulus.

...

Code Block
bgColorCCCCFF
private int size=16;
	
public int[] hashTable=new int[size];
	
public int lookup(int hash)
{
  if(hash < 0)
    return hashTable[(-hash) % size];
  return hashTable[hash % size];
}

Risk Assessment

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

INT36-J

low

unlikely

high

P1

L3

Automated Detection

Unknown

Other Languages

This rule appears in the C Secure Coding Standard as INT10-C. Do not assume a positive remainder when using the % operator, and 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]