Division and modulo operations are susceptible to divide-by-zero errors. According to section C11, Section 6.5.5, paragraph 5 of para. 5 [ISO/IEC 9899:19992011],
The result of the
/
operator is the quotient from the division of the first operand by the second; the result of the%
operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
(See also undefined behavior 42 45 of Annex J.)
Division
The result of the /
operator is the quotient from the division of the first arithmetic operand by the second arithmetic operand. Division operations are susceptible to divide-by-zero errors. Overflow can also occur during two's complement signed integer division when the dividend is equal to the minimum (negative) value for the signed integer type and the divisor is equal to —1−1. (See rule INT32-C. Ensure that operations on signed integers do not result in overflow.)
...
Code Block | ||||
---|---|---|---|---|
| ||||
signed long sl1, sl2, result;
/* Initialize sl1 and sl2 */
result = sl1 / sl2;
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
signed long sl1, sl2, result;
/* Initialize sl1 and sl2 */
if ( (sl2 == 0) || ( (sl1 == LONG_MIN) && (sl2 == -1) ) ) {
/* handle error condition */
}
else {
result = sl1 / sl2;
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
signed long sl1, sl2, result;
/* Initialize sl1 and sl2 */
result = sl1 % sl2;
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
signed long sl1, sl2, result;
/* Initialize sl1 and sl2 */
if ( (sl2 == 0 ) || ( (sl1 == LONG_MIN) && (sl2 == -1) ) ) {
/* handle error condition */
}
else {
result = sl1 % sl2;
}
|
...
Tool | Version | Checker | Description | section|||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
| ||||||||||||
Section | 43 D | sectionPartially | Implemented sectionimplemented. | |||||||||
Fortify SCA | sectionV. 5.0 | |||||||||||
Section | Can detect violations of this rule with CERT C Rule Pack | section|||||||||||
Compass/ROSE | ||||||||||||
Section | Can detect some violations of this rule. In particular, it ensures that all operations involving division or modulo are preceded by a check ensuring that the second operand is non-zero. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: INT33-CPP. Ensure that division and modulo operations do not result in divide-by-zero errors
ISO/IEC 9899:1999 Section 6.5.5, "Multiplicative operators"
The CERT Oracle Secure Coding Standard for Java: NUM02-J. Ensure that division and modulo operations do not result in divide-by-zero errors
ISO/IEC 9899:2011 Section 6.5.5, "Multiplicative operators"
ISO/IEC TR 17961 (Draft) Dividing by zero [divzero]
MITRE CWE: CWE-369, "Divide By Zero"
...