DBZ.ITERATOR.FLOAT

Loop iterator might be used in a division by floating-point zero

An attempt to do a division or modulo operation using zero as the divisor causes a runtime error. Division by zero defects often occur due to ineffective error handling or race conditions, and typically cause abnormal program termination. Before a value is used as the divisor of a division or modulo operation in C/C++ code, it must be checked to confirm that it is not equal to zero.

The DBZ checkers look for instances in which a zero constant value is used as the divisor of a division or modulo operation.

The DBZ.ITERATOR.FLOAT checker flags situations in which a loop iterator that has been assigned a zero constant value in the execution of the loop might later be used as a divisor in a division or modulo operation without first being checked for a zero value.

Vulnerability and risk

Integer division by zero usually results in the failure of the process or in an exception. It can also result in the success of the operation, but gives an erroneous answer. Floating-point division by zero is more subtle. It depends on the implementation of the compiler. If the compiler is following the IEEE floating-point standard (IEEE 754), then the result of the floating-point division by zero has a well-defined result. However, the C and C++ standards do not enforce compliance to IEEE 754. Thus, floating-point division by zero has an undefined behavior in C and C++ and might result in the failure of the process or in an exception.

Mitigation and prevention

Division by zero issues typically occur due to ineffective exception handling. To avoid this vulnerability, check for a zero value before using it as the divisor of a division or modulo operation.

Vulnerable code example

Copy
double count_sum_of_custom_arithmetic_series_defect() {
    for (float i = -1.0f; i <= 2.0f; i += 0.5f) {
        float result = 10.0f / i; //DBZ.ITERATOR.FLOAT
    }
   return 10.0f;
}

Klocwork reports DBZ.ITERATOR.FLOAT at Line 3 where loop iterator 'i' might be used in a division by floating-point zero.

Fixed code example

Copy
double count_sum_of_custom_arithmetic_series_fixed() {
    for (float i = -1.0f; i <= 2.0f; i += 0.5f) {
        if(i != 0.0f)
            float result = 10.0f / i; //no DBZ.ITERATOR.FLOAT
    }
   return 10.0f;
}

There is no possibility of a DBZ.ITERATOR.FLOAT, as the check prevents division by zero.

External guidance