...
- integer operands of any pointer arithmetic, including array indexing;
- the assignment expression for the declaration of a variable length array;
- the postfix expression preceding square brackets
[]
or the expression in square brackets[]
of a subscripted designation of an element of an array object; and
function arguments of type size_t
or rsize_t
(for example, an argument to a memory allocation function).
The C Standard defines arithmetic on atomic integer types as read-modify-write operations with the same representation as non-atomic integer types. As a result, wrapping of atomic unsigned integers is identical to non-atomic unsigned integers and should also be prevented or detected.
Anchor | ||||
---|---|---|---|---|
|
Addition
...
The left-shift operator takes two operands of integer type. For examples of usage of the left-shift operator, see INT34-C. Do not shift a negative number of bits or more bits than exist in the operand.
Atomic Integers
The C Standard defines arithmetic on atomic integer types as read-modify-write operations with the same representation as non-atomic integer types. As a result, wrapping of atomic unsigned integers is identical to non-atomic unsigned integers and should also be prevented or detected.
This section includes an example only for the addition of atomic integer types. For other operations, you can use tests similar to the precondition tests for non-atomic integer types.
Noncompliant Code Example
This noncompliant code example using atomic integers can result in unsigned integer overflow wrapping:
...
...
...
Compliant Solution
This compliant solution performs a postcondition test to ensure that the result of the unsigned addition operation to i
is not less than the operand a
. However, this code contains a race condition where i
can be modified after the addition, but prior to the atomic load. This solution is only compliant if i
is guaranteed to only be access by a single thread. See CON08-C. Do not assume that a group of calls to independently atomic methods is atomic for more information.
bgColor | #ccccff |
---|---|
lang | c |
Exceptions
INT30-EX1. Unsigned integers can exhibit modulo behavior (wrapping) when necessary for the proper execution of the program. It is recommended that the variable declaration be clearly commented as supporting modulo behavior and that each operation on that integer also be clearly commented as supporting modulo behavior.
...