Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Consequently, it is difficult to write portable safe code that makes assumptions regarding the layout of structure members, and it is impossible to write portable code that makes assumptions about the layout of bit-field structures.

This rule is similar to ARR37-C. Do not add or subtract an integer to a pointer to a non-arrayobjectarray object

Non-Compliant Code Example (Bit-Field Alignment)

...

Code Block
bgColor#ffcccc
struct bf {
  unsigned int m1 : 8;
  unsigned int m2 : 8;
  unsigned int m3 : 8;
  unsigned int m4 : 8;
}; /* 32 bits total */

void function() {
  struct bf data;
  unsigned char *ptr;

  data.m1 = 0;
  data.m2 = 0;
  data.m3 = 0;
  data.m4 = 0;
  ptr = (unsigned char *)&data;
  (*ptr)++; /* could increment data.m1 or data.m4 */
}

This code also violates ARR37-C. Do not add or subtract an integer to a pointer to a non-arrayobjectarray object

Compliant Solution (Bit-Field Alignment)

...

In the above example, if each bit-field lives within its own byte, then m2 (or m1, depending on alignment) is incremented by 1. If the bit-fields are indeed packed across 8-bit bytes, then m2 might be incremented by 4.

This code also violates ARR37-C. Do not add or subtract an integer to a pointer to a non-arrayobjectarray object

Compliant Solution (Bit-Field Overlap)

...

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.2, "Type specifiers"
\[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "STR Bit Representations"
\[[MISRA 04|AA. C References#MISRA 04]\] Rule 3.5
\[[Plum 85|AA. C References#Plum 85]\] Rule 6-5

...

INT10EXP10-A. Do not assume a positive remainder when using the % operator      04. Integers (INT)       INT12-A. Do not make assumptions about the type of a plain int bit-field when used in an expressiondepend on the order of evaluation of subexpressions or the order in which side effects take place      03. Expressions (EXP)       EXP30-C. Do not depend on order of evaluation between sequence points