除算と剰余演算ではゼロ除算エラーが発生する可能性がある。そのため、除算や剰余演算を行う前に、除数がゼロでないかをチェックする必要がある。
違反コード (除算)
除算演算子 / の結果は第1オペランドを第2オペランドで割った商となる。除算ではゼロ除算エラーが発生する可能性がある。また、2の補数表現において被除数が符号付き整数型の最小値(負の値)、除数が-1 の場合、オーバーフローが発生する。(「NUM00-J. 整数オーバーフローを検出あるいは防止する」を参照)。
以下の違反コード例では、符号付きオペランド num1 と num2 の除算時にゼロ除算エラーが発生する可能性がある。
long num1, num2, result; /* num1 と num2 を初期化 */ result = num1 / num2;
適合コード (除算)
以下の適合コードでは、ゼロ除算エラーが発生しないよう、第2オペランドを検査している。
long num1, num2, result; /* num1 と num2 を初期化 */ if (num2 == 0) { // エラー処理 } else { result = num1 / num2; }
違反コード (剰余演算)
剰余演算子 % は、2つの整数型オペランドによる除算の剰余を計算する。符号付きオペランド num1 と num2 による剰余演算でゼロ除算エラーが発生する可能性がある。
long num1, num2, result; /* num1 と num2 を初期化 */ result = num1 % num2;
適合コード
以下の適合コードでは、ゼロ除算エラーが発生しないよう、第2オペランドを検査している。
long num1, num2, result; /* num1 と num2 を初期化 */ if (num2 == 0) { // エラー処理 } else { result = num1 % num2; }
リスク評価
ゼロ除算エラーはプログラムの異常終了やサービス運用妨害につながる可能性がある。
ルール | 深刻度 | 可能性 | 修正コスト | 優先度 | レベル |
---|---|---|---|---|---|
NUM02-J | 低 | 高 | 中 | P6 | L2 |
自動検出
CおよびC++における自動検出ツールは存在するが、Javaではまだ存在しない。
関連ガイドライン
CERT C Secure Coding Standard | INT33-C. Ensure that division and modulo operations do not result in divide-by-zero errors |
CERT C++ Secure Coding Standard | INT33-CPP. Ensure that division and modulo operations do not result in divide-by-zero errors |
MITRE CWE | CWE-369. Divide by zero |
参考文献
[ISO/IEC 9899:1999] | Section 6.5.5, Multiplicative operators |
[Seacord 05] | Chapter 5, Integers |
[Warren 02] | Chapter 2, Basics |
翻訳元
これは以下のページを翻訳したものです。
NUM02-J. Ensure that division and modulo operations do not result in divide-by-zero errors (revision 38)