Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

MISRA.SHIFT.RANGE.2012

Right operand of shift operation is out of range - greater or equal to the essential type size of left operand, or is negative.

MISRA C 2012 Rule 12.2: 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

C90 [Undefined 32], C99 [Undefined 48]

Category: Required

Analysis: Undecidable, System

Applies to: C90, C99

Rationale

If the right hand operand is negative, or greater than or equal to the width of the left hand operand, then the behaviour is undefined.

If, for example, the left hand operand of a left-shift or right-shift is a 16-bit integer, then it is important to ensure that this is shifted only by a number in the range 0 to 15.

See Section 8.10 for a description of essential type and the limitations on the essential types for the operands of shift operators.

There are various ways of ensuring this rule is followed. The simplest is for the right hand operand to be a constant (whose value can then be statically checked). Use of an unsigned integer type will ensure that the operand is non-negative, so then only the upper limit needs to be checked (dynamically at run time or by review). Otherwise both limits will need to be checked.

Example

u8a = u8a << 7;                /* Compliant     */
u8a = u8a << 8;                /* Non-compliant */
u16a = ( uint16_t ) u8a << 9;  /* Compliant     */

To assist in understanding the following examples, it should be noted that the essential type of 1u is essentially unsigned char, whereas the essential type of 1UL is essentially unsigned long.

1u << 10u;                     /* Non-compliant */
( uint16_t ) 1u << 10u;        /* Compliant     */
1UL << 10u;                    /* Compliant     */