ATH-shift-bounds
Synopsis
Out of range shifts were found.
Enabled by default
Yes
Severity/Certainty
Medium/Medium

Full description
The right-hand operand of a shift operator might be negative or too large. A shift operator on an n-bit argument should only shift between 0 and n-1 bits. The behavior here is undefined; the code might work as intended, or data could become erroneous. This check is identical to MISRAC2004-12.8, MISRAC++2008-5-8-1, MISRAC2012-Rule-12.2.
Coding standards
- CERT INT34-C
Do not shift a negative number of bits or more bits than exist in the operand
- CWE 682
Incorrect Calculation
- MISRA C:2004 12.8
(Required) The right-hand operand of a shift operator shall lie between zero and one less than the width in bits of the underlying type of the left-hand operand.
- MISRA C:2012 Rule-12.2
(Required) The right hand operand of a shift operator shall lie in the range zero to one less than the width in bits of the essential type of the left hand operand
- MISRA C++ 2008 5-8-1
(Required) The right hand operand of a shift operator shall lie between zero and one less than the width in bits of the underlying type of the left hand operand.
Code examples
The following code example fails the check and will give a warning:
unsigned int foo(unsigned int x, unsigned int y)
{
int shift = 33; // too big
return 3U << shift;
}
The following code example passes the check and will not give a warning about this issue:
unsigned int foo(unsigned int x)
{
int y = 1; // OK - this is within the correct range
return x << y;
}