MISRA.SHIFT.RANGE.2012Right 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 operandC90 [Undefined 32], C99 [Undefined 48] Category: Required Analysis: Undecidable, System Applies to: C90, C99 RationaleIf 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. Exampleu8a = 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 */ |