Division or modulo by a denominator that is always zero
ID |
c.correctness.division_by_zero |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Numeric Operation |
Language |
C / C++ |
Description
Reports a / or % operation whose right-hand operand is the literal 0, or a variable whose value is provably 0 at the point of use because it was initialized to 0 and never reassigned.
Rationale
Integer division and modulo by zero are undefined behavior in C and C++; on the common platforms this raises SIGFPE and terminates the process rather than producing a special value the way floating-point division does. When the denominator is a literal 0, or a variable that constant folding shows is still 0, the crash is not a rare edge case that depends on input - it happens on every execution that reaches the line.
The following code illustrates the pattern detected by this rule:
void report(int n, int m)
{
// FLAGGED: Division or modulo by a denominator that is always zero
int a = n / 0;
// FLAGGED: Division or modulo by a denominator that is always zero
int b = n % 0;
int d = 0;
// FLAGGED: Division or modulo by a denominator that is always zero
int c = n / d;
int e = n / m;
int g = 5;
int h = n / g;
int i = n / 1;
int reassigned = 0;
reassigned = 5;
int j = n / reassigned;
}