Java


JAVA.MATH.ABSRAND : Abs on random (Java)

要旨

The absolute value of a random number might actually be negative.

By computing the absolute value of a random integral number, one might actually yield a negative number, if Math.abs() is used. For instance, System.out.println(Math.abs(Integer.MIN_VALUE)) would actually print the negative value -2147483648. As a consequence, this might result in unexpected or erroneous computations.

プロパティ

クラス名 Abs on random (Java)
日本語クラス名 Abs on random (Java)
クラス分類 信頼性 (reliability)
ニーモニック JAVA.MATH.ABSRAND
カテゴリー
CWE CWE:682 Incorrect Calculation
CERT-Java CERT-Java:NUM00-J Detect or prevent integer overflow
対応言語 Java で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Abs on random (Java)"

Consider the following program:

import java.util.Random;

public class AbsOfRandom {

  public static void main(String[] args) {
    Random r = new Random();
    int i = r.nextInt();  // "Abs on random (Java)" warning issued here
    i = Math.abs(i);

    System.out.println(i);       // i may contain Integer.MIN_VALUE, which is negative
  }
}

In this example, the programmer should check for the minimum integral value explicitly, as in the following example.

    Random r = new Random();
    int i = r.nextInt();
    if (i == Integer.MIN_VALUE)
    i = 0; // any non-negative value would do
    else if (i < 0)
      i = -i;

    System.out.println(i);

解決法

Check, explicitly, for the minimal integral value, before computing the absolute value. Otherwise, since Java 15, java.lang.Math.absExact and java.lang.StrictMath.absExact allows to compute the absolute values in a safe way, throwing ArithmeticException if the result overflows.

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。