Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added Math.abs() NCCE/CS samples

...

While this statement is true, arithmetic operations in the Java platform require just as much caution as their analogous operations in C and C++ do , because integer operations in Java can still result in overflow. Java does not provide any indication of overflow conditions and silently wraps. While integer overflows in vulnerable C and C++ programs can result in the execution of arbitrary code; in Java, wrapped values typically result in incorrect computations and unanticipated outcomes.

...

Code Block
bgColor#ccccff
private static final BigInteger bigMaxInt = BigInteger.valueOf(Int.MAX_VALUE);
private static final BigInteger bigMinInt = BigInteger.valueOf(Int.MIN_VALUE);

public static BigInteger intRangeCheck(BigInteger val) throws ArithmeticException {
  if (val.compareTo(bigMaxInt) == 1 ||
      val.compareTo(bigMinInt) == -1) {
    throw new ArithmeticException("Integer overflow");
  }
  return val;
}

public static int multAccum(int oldAcc, int newVal, int scale) throws ArithmeticException { 
  BigInteger product =
    BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
  BigInteger res = intRangeCheck(BigInteger.valueOf(oldAcc).add(product));
  return res.intValue(); // safe conversion
}

Noncompliant Code Example (Math.abs())

Overflow is also possible via the java.lang.Math.abs() function, which returns a number's absolute value.

Code Block
bgColor#FFcccc

public int magnitude(int i) {
  return Math.abs(i);
}

If Integer.MIN_VALUE (–2,147,483,648) is passed to Math.abs(), the result is Integer.MIN_VALUE, not -Integer.MIN_VALUE, because -Integer.MIN_VALUE is not representable as an int.

Compliant Solution (Math.abs())

This compliant solution uses the pre-condition testing approach to safely return the absolute value of a number.

Code Block
bgColor#ccccff

static final int preAbs(int i) throws ArithmeticException {
  if (i == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
  return Math.abs(i);
}

public int magnitude(int i) throws ArithmeticException {
  return preAbs(i);
}

Noncompliant Code Example AtomicInteger

...