...
The assertion fails if long long
has less than twice the width of int
. The PRECISION()
macro and popcount()
function are explained in INT35-C. Use correct integer precisions.
Compliant Solution
The following portable compliant solution can be used for on any conforming implementation, including those that do not have an integer type that is at least twice as big as int
.:
...
This noncompliant code example prevents divide-by-zero errors in compliance with INT33-C. Ensure that division and remainder operations do not result in divide-by-zero errors but does not prevent a signed integer overflow error on twos-complement platforms. On the x86-32 architecture, overflow results in a fault, which can be exploited as a denial-of-service attack.
Code Block | ||||
---|---|---|---|---|
| ||||
void func(signed long s_a, signed long s_b) { signed long result; if (s_b == 0) { /* Handle error */ } else { result = s_a / s_b; } /* ... */ } |
Implementation Details
On the x86-32 architecture, overflow results in a fault, which can be exploited as a denial-of-service attack.
Compliant Solution
This compliant solution eliminates the possibility of divide-by-zero errors or signed overflow:
...
Code Block | ||||
---|---|---|---|---|
| ||||
void func(signed long s_a, signed long s_b) { signed long result; if (s_b == 0) { /* Handle error */ } else { result = s_a % s_b; } /* ... */ } |
Implementation Details
On x86 platforms, the remainder operator for signed integers is implemented by the idiv
instruction code, along with the divide operator. Because LONG_MIN / -1
overflows, this code will throw a floating-point exception on LONG_MIN % -1
.
...
The C Standard, 6.5.7 paragraph 4 [ISO/IEC 9899:2011], states
...
In almost every case, an attempt to shift by a negative number of bits or by more bits than exist in the operand indicates a bug (logic error). These issues are covered by INT34-C. Do not shift a negative number of bits or more bits than exist in the operand.
Noncompliant Code Example
This noncompliant code example can result in an unrepresentable value.
...
Compliant Solution
This compliant solution eliminates the possibility of overflow resulting from a left-shift operation:
...