SEC-DIV-0-compare-before
Synopsis
A variable is first used as a divisor, then compared with 0.
Enabled by default
Yes
Severity/Certainty
Low/High

Full description
A variable is compared to 0 after it is used as a divisor, but before it is written to again. The comparison implies that the variable's value might be 0, and might have been for the preceding statements. Because one of these statements is an operation that uses the variable as a divisor (which would cause a 'divide by zero' runtime error), the execution can never reach the comparison when the value is 0, making it meaningless. This check is identical to ATH-div-0-cmp-bef, MISRAC2004-1.2_f, MISRAC2012-Rule-1.3_d, CERT-INT33-C_c.
Coding standards
- CERT INT33-C
Ensure that division and modulo operations do not result in divide-by-zero errors
- CWE 369
Divide By Zero
- MISRA C:2004 1.2
(Required) No reliance shall be placed on undefined or unspecified behavior.
- MISRA C:2012 Rule-1.3
(Required) There shall be no occurrence of undefined or critical unspecified behaviour
Code examples
The following code example fails the check and will give a warning:
int foo(int p)
{
int a = 20, b = 1;
b = a / p;
if (p == 0) // Checking the value of 'p' too late.
return 0;
return b;
}
The following code example passes the check and will not give a warning about this issue:
int foo(int p)
{
int a = 20, b;
if (p == 0)
return 0;
b = a / p; /* Here 'p' is non-zero. */
return b;
}