...
The result of E1 << E2
is E1
left-shifted E2
bit positions; vacated bits are filled with zeros. If E1
has a signed type and nonnegative value , and E1 * 2 E2
is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
...
The following code can result in undefined behavior because there is no check to ensure that left and right operands have nonnegative values , and that the right operand is greater than or equal to the width of the promoted left operand.
...
In C99, the CHAR_BIT
macro defines the number of bits for the smallest object that is not a bit-field (byte). A byte, therefore, contains CHAR_BIT
bits.
...
Wiki Markup |
---|
The result of {{E1 << E2}} is {{E1}} left-shifted {{E2}} bit positions; vacated bits are filled with zeros. According to C99, if {{E1}} has an unsigned type, the value of the result is {{E1 * 2 ^E2^^E2{^}}}, reduced modulo one more than the maximum value representable in the result type. Although C99 specifies modulo behavior for unsigned integers, unsigned integer overflow frequently results in unexpected values and resultant security vulnerabilities (see \[[INT32-C|INT32-C. Ensure that integer operations do not result in an overflow]\]). Consequently, unsigned overflow is generally non-compliant and {{E1 * 2 ^E2^^E2{^}}} must be representable in the result type. Modulo behavior is allowed if the conditions in the exception section are met. |
The following code can result in undefined behavior because there is no check to ensure that the right operand is greater than or equal to the width of the promoted left operand.
...
This non-compliant code example fails to test if whether the right operand is negative or is greater than or equal to the width of the promoted left operand, allowing undefined behavior.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
INT36-C | 2 (medium) | 2 (probable) | 2 (medium) | P8 | L2 |
References
A test program for this rule is available.
Wiki Markup |
---|
\[[Dowd 06|AA. C References#Dowd 06]\] Chapter 6, "C Language Issues"
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.5.7, "Bitwise shift operators"
\[[Seacord 05|AA. C References#Seacord 05]\] Chapter 5, "Integers"
\[[Viega 05|AA. C References#Viega 05]\] Section 5.2.7, "Integer overflow"
\[[ISO/IEC 03|AA. C References#ISO/IEC 03]\] Section 6.5.7, "Bitwise shift operators" |