...
This solution is also compliant with rule INT34-C. Do not shift a negative number of bits or more bits than exist in the operand.
Atomic Integers
Note that according to the The C Standard [ISO/IEC 9899:2011] , the defines the behavior of arithmetic on atomic signed integer types is defined to use two's complement representation with silent wrap-around on overflow; there are no technically undefined results. However, while defined, these results are still may be unexpected and thus therefore carry similar risks , and have similar solutions to non-atomic integers.to unsigned integer wrapping (see INT30-C. Ensure that unsigned integer operations do not wrap). Consequently, signed integer overflow of atomic integer types should also be prevented or detected.
Noncompliant Code Example
...
This compliant solution tests the operands to guarantee there is no possibility of signed overflow, regardless of representation. It loads the value stored in the atomic integer and tests for overflow as previously determined abovepossible overflow before performing the addition.
Code Block | ||||
---|---|---|---|---|
| ||||
atomic_int i; int si1; /* Initialize si1, i */ int si2 = atomic_load(&i); if (((si2>0) && (si1 > (INT_MAX-si2))) || ((si2<0) && (si1 < (INT_MIN-si2)))) { /* handle error condition */ } else { atomic_fetch_add(&i, si1); } |
...