 
                            Do not assume that a right shift operation is implemented as either an arithmetic (signed) shift or a logical (unsigned) shift. If E1 in the expression E1 >> E2 has a signed type and a negative value, the resulting value is implementation-defined and may be either an arithmetic shift or a logical shift. Also, be careful to avoid undefined behavior while performing a bitwise shift [[INT36-C. Do not shift a negative number of bits or more bits than exist in the operand]].
Non-Compliant Code Example
This non-compliant code example can result in a buffer overflow on implementations in which an arithmetic shift is performed and the sign bit can be propagated as the number is shifted [[Dowd 06]].
int stringify;
char buf[sizeof("256")];
sprintf(buf, "%u", stringify >> 24);
For example, if stringify has the value 0x80000000, stringify >> 24 evaluates to 0xFFFFFF80 and the subsequent call to sprintf() results in a buffer overflow.
Compliant Solution
For bit extraction, make sure to mask off the bits you are not interested in.
	#ifdef _MSC_VER
	#define sprintf_secure sprintf_s
	#else
	#define sprintf_secure snprintf
	#endif
	int stringify = 0x80000000;
	char buf[sizeof("256")];
	sprintf_secure(buf, sizeof("256"), "%u", ((stringify >> 24) & 0xff)); 
Risk Assessment
Improper range checking can lead to buffer overflows and the execution of arbitary code by an attacker.
| Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level | 
|---|---|---|---|---|---|
| INT13-A | 3 (high) | 1 (unlikely) | 2 (medium) | P6 | L2 | 
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[Dowd 06]] Chapter 6, "C Language Issues"
[[ISO/IEC 9899-1999]] Section 6.5.7, "Bitwise shift operators"
[[ISO/IEC 03]] Section 6.5.7, "Bitwise shift operators"
INT12-A. Do not make assumptions about the type of a bit-field when used in an expression 04. Integers (INT) INT14-A. Distinguish bitmaps from numeric types