Divide By Zero. High

Software flaws related to dividing by zero or performing other arithmetic operations that result in a divide-by-zero condition, can lead to unexpected behavior, application crashes, or security vulnerabilities if not properly handled.

Detector ID
c/divide-by-zero@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1struct OptionalInt divideByZeroNonCompliant(int a, int b) {
2   struct OptionalInt result;
3  // While the following check correctly prevents signed integer overflows,
4  // it fails to prevent divide-by-zero errors. If `b` is equal to `0`, the
5  // application emits undefined behavior.
6  if ((a == INT_MIN) && (b == -1)) {
7    result.has_value = 0;
8    return result;
9  }
10  result.has_value = 1;
11  // Noncompliant: Performing division without checking if the denominator is zero will lead to division by zero errors
12  result.value = a / b; 
13  return result; // causes undefined behavior if `b` is zero
14}

Compliant example

1struct OptionalInt divideByZeroCompliant(int a, int b) {
2    struct OptionalInt result;
3
4    if ((b == 0) || ((a == INT_MIN) && (b == -1))) {
5        result.has_value = 0; // Indicates failure
6        return result;
7    }
8    
9    result.has_value = 1;
10    // Compliant: Checking if the denominator is zero before dividing to avoid division by zero errors
11    result.value = a / b; 
12    return result; // Check correctly prevents divide-by-zero and signed integer overflows
13}