...
This compliant solution uses the GNU extension __builtin_sadd_overflow
, available with GCC, Clang, and ClangICC:
Code Block | ||||
---|---|---|---|---|
| ||||
void f(signed int si_a, signed int si_b) { signed int sum; if (__builtin_sadd_overflow(si_a, si_b, &sum)) { /* Handle error */ } /* ... */ } |
...
This compliant solution uses the GNU extension __builtin_ssub_overflow
, available with GCC, Clang, and ClangICC:
Code Block | ||||
---|---|---|---|---|
| ||||
void func(signed int si_a, signed int si_b) { signed int diff; if (__builtin_ssub_overflow(si_a, si_b, &diff)) { /* Handle error */ } /* ... */ } |
...
This compliant solution uses the GNU extension __builtin_smul_overflow
, available with GCC, Clang, and ClangICC:
Code Block | ||||
---|---|---|---|---|
| ||||
void func(signed int si_a, signed int si_b) { signed int result; if (__builtin_smul_overflow(si_a, si_b, &result)) { /* Handle error */ } } |
...
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 logic error. These issues are covered by INT34-C. Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand.
Noncompliant Code Example
This noncompliant code example performs a left shift, after verifying that the number being shifted is not negative, and the number of bits to shift is valid. The PRECISION()
macro and popcount()
function provide the correct precision for any integer type. (See INT35-C. Use correct integer precisions.) However, because this code does no overflow check, it can result in an unrepresentable value.
...
Compliant Solution
This compliant solution eliminates the possibility of overflow resulting from a left-shift operation:
...