V2555. MISRA. Incorrect shifting expression.

This diagnostic rule is based on the software development guidelines developed by MISRA (Motor Industry Software Reliability Association).

In a bitwise shift operation, the value of the right operand must be within the range [0 .. N - 1], where N is the number of bits representing the left operand. Failing to follow this rule leads to undefined behavior.

Example of non-compliant code:

(int32_t) 1 << 128u;
(unsigned int64_t) 2 >> 128u;
int64_X >>= 64u;
any_var << -2u;

The following example is a snippet from a real application, where an incorrect bitwise shift operation results in undefined behavior:

UINT32 m_color1_mask;
UINT32 m_color2_mask;

#define ARRAY_LENGTH(x) (sizeof(x) / sizeof(x[0]))

PALETTE_INIT( montecar )
 static const UINT8 colortable_source[] =
  0x00, 0x00, 0x00, 0x01,
  0x00, 0x02, 0x00, 0x03,
  0x03, 0x03, 0x03, 0x02,
  0x03, 0x01, 0x03, 0x00,
  0x00, 0x00, 0x02, 0x00,
  0x02, 0x01, 0x02, 0x02,
  0x00, 0x10, 0x20, 0x30,
  0x00, 0x04, 0x08, 0x0c,
  0x00, 0x44, 0x48, 0x4c,
  0x00, 0x84, 0x88, 0x8c,
  0x00, 0xc4, 0xc8, 0xcc
 for (i = 0; i < ARRAY_LENGTH(colortable_source); i++)
  UINT8 color = colortable_source[i];

  if (color == 1)
   state->m_color1_mask |= 1 << i;                  // <=
  else if (color == 2)
   state->m_color2_mask |= 1 << i;                  // <=

  prom_to_palette(machine, i,
    color_prom[0x100 + colortable_source[i]]);

The value 1 is shifted by i bits to the left at the i-th iteration of the loop. Starting with the 32-nd iteration (given that int is a 32-bit type), the 'i' variable will be taking values within the range [0 .. 43], which is larger than the allowed range.

This diagnostic is classified as:

  • MISRA-C-12.2
  • MISRA-CPP-5.8.1
  • AUTOSAR-M5.8.1

Bugs Found

Checked Projects
Collected Errors
14 132
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site. Learn More →