...
The result of E1 >> E2
is E1
}} right-shifted E2
bit positions. If E1
has an unsigned type or if E1
has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2 E2
. If E1
has a signed type and a negative value, theresulting the resulting value is implementation-defined.This code can result in an unsigned overflow during the shift operation of the unsigned operands ui1
and ui2
. If this behavior is unanticipated, the resulting value may be used to allocate insufficient memory for a subsequent operation or in some other manner that could lead to an exploitable vulnerability.
Code Block | ||
---|---|---|
| ||
signed int si1, si2, resultsresult; unsigned int ui1, ui2, uresult; resultsresult = si1 >> si2; uresult = ui1 >> ui2; |
Compliant Solution (
...
rightshift)
This compliant solution tests the suspect shift operation to guarantee there is no possibility of unsigned overflow.
Code Block | ||
---|---|---|
| ||
int si1, si2, sresult; unsigned int ui1, ui2, result; if ( (si1 < 0) || (ui2si2 < 0) || (si2 >= sizeof(int)*CHAR_BIT) ) { /* handle error condition */ } else { sresult = si1 >> si2; } if (ui2 >= sizeof(unsigned int)*CHAR_BIT) ) { /* handle error condition */ } resultelse { uresult = ui1 >> ui2; } |
Exceptions
Unsigned integers can be allowed to exhibit modulo behavior if and only if
...
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, "Expressions," and Section 7.10.7, "SizesBitwise of integer types <limits.h>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" |