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

Description

Rule Definition

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.

Rationale

Consider this statement:

var = abc << num;
If abc is a 16-bit integer, then num must be in the range 0–15, (nonnegative and less than 16). If num is negative or greater than 16, then the shift behavior is undefined.

Polyspace Implementation

Polyspace® raises a violation when the right operand of a shift operator exceeds the range defined in this rule. When the right operand is a variable, the violation is raised unless all possible value of the operand remains within the range defined in this rule.

In Polyspace, the numbers that are manipulated in preprocessing directives are 64 bits wide. The valid shift range is between 0 and 63. When bitfields are within a complex expression, Polyspace extends this check onto the bitfield field width or the width of the base type.

Additional Message in Report

  • Shift amount is bigger than size.

  • Shift amount is negative.

  • The right 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 operand.

Troubleshooting

If you expect a rule violation but do not see it, refer to the documentation of Polyspace Code Prover™ or Polyspace Code Prover Server™.

Examples

expand all

void foo(void) {
  int i;
  unsigned int BitPack = 0U;
  
  for (i = 0; i < 32; i++) {
    BitPack |= (1U << ((unsigned int)i));  //Noncompliant
  }
}

In this example, the left operand 1U of the shift operator has an essential type unsigned char. Acceptable values for the right operand lies in the range from zero to seven. Because the right operand i ranges from zero to 31, Polyspace flags the shift operation.

Check Information

Group: Expressions
Category: Required
AGC Category: Required