Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider $version (sch jbop) (X_X)@==(Q_Q)@

...

Bit-field types other than _Bool, int, signed int, and unsigned int are implementation-defined.  They still obey the integer promotions quoted above when the specified width is at least as narrow as CHAR_BIT*sizeof(int), but wider bit-fields are not portable.

...

Noncompliant Code Example

This non-compliant noncompliant code depends on implementation-defined behavior.  It prints either -1 or 255 depending on whether a plain int bit-field is signed or unsigned.

Code Block
bgColor#FFcccc
struct {
  int a: 8;
} bits = {255};

int main(void) {
  printf("bits.a = %d.\n", bits.a);
  return 0;
}

Compliant Solution

This compliant solution uses an unsigned int bit-field and does not depend on implementation-defined behavior.

Code Block
bgColor#ccccff
struct {
  unsigned int a: 8;
} bits = {255};

int main(void) {
  printf("bits.a = %d.\n", bits.a);
  return 0;
}

Risk Assessment

Making invalid assumptions about the type of a bit-field or its layout can result in unexpected program flow.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

INT12-A C

low

unlikely

medium

P2

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

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 12.7

...

INT11-C. Take care when converting from pointer to integer or integer to pointer      04. Integers (INT)       INT13-A. Use bitwise operators only on unsigned operands Image Added