Bit-fields can be used to allow flags or other integer values with small ranges to be packed together to save storage space.
It is implementation-defined whether the specifier int
designates the same type as signed int
or the same type as unsigned int
for bit - fields. According to C99 to the C standard [ISO/IEC 9899:19992011], C integer promotions also require that "if an int
can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int
; otherwise, it is converted to an unsigned int
."
This is a similar issue This issue is similar to the signedness of plain char
, discussed in recommendation INT07-C. Use only explicitly signed or unsigned char type for numeric values. A plain int
bit-field that is treated as unsigned will promote to int
, as long as its field width is less than that of int
because int
can hold all values of the original type. This is the same behavior as that of a plain char
treated as unsigned. However, a plain int
bit-field treated as unsigned will promote to unsigned int
, if its field width is the same as that of int
. This difference makes a plain int
bit-field even trickier than a plain char
.
Bit-field types other than _Bool
, int
, signed int
, and unsigned int
are implementation-defined. They still obey the integer promotions quoted above previously when the specified width is at least as narrow as CHAR_BIT*sizeof(int)
, but wider bit-fields are not portable.
...
This 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 | ||||
---|---|---|---|---|
| ||||
struct {
int a: 8;
} bits = {255};
int main(void) {
printf("bits.a = %d.\n", bits.a);
return 0;
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
struct {
unsigned int a: 8;
} bits = {255};
int main(void) {
printf("bits.a = %d.\n", bits.a);
return 0;
}
|
...
Tool | Version | Checker | Description | section|||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
| Section | 73 S section | Fully Implementedimplemented | |||||||||
Section | Compass/ROSE |
|
|
| ||||||||
Section | |
| Section | bitftype Section | | Fully Implementedimplemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: INT12-CPP. Do not make assumptions about the type of a plain int bit-field when used in an expression
ISO/IEC 9899:19992011 Section 6.3.1.1, "Boolean, characters, and integers," and Section 6.7.2, "Type specifiers"
...