Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the type of bitfield affect structure alignement

Tags:

c

struct

bit

I have the following structures:

struct bf_struct1
{
    uint64_t bf1 : 1;
    uint64_t bf2 : 6;
    uint64_t bf3 : 2;
    uint64_t bf4 : 55;
}

struct bf_struct2
{
    uint8_t bf1 : 1;
    uint8_t bf2 : 6;
    uint8_t bf3 : 2;
    uint64_t bf4 : 55;
}

Does the structure member alignment depend on type of a bitfield members?

like image 807
Alex Avatar asked Oct 12 '25 21:10

Alex


2 Answers

  • The alignment of the bit field as whole is unspecified behavior and whether a bit field is allowed to allocate unaligned is implementation-defined behavior.
  • The the bit order of a bit field is implementation-defined.
  • Because of the two remarks above, the compiler is free to add padding bits and padding bytes anywhere inside a bit field, as it pleases, in an implementation-defined manner.
  • Whether uint64_t is actually allowed inside a bit field is implementation-defined. So the code might not even work.

There is really no way to tell what this code will even do, let alone how it will be affected by alignment, without reading up on the documentation for a specific compiler.

like image 137
Lundin Avatar answered Oct 14 '25 16:10

Lundin


From the horse's mouth:

6.7.2.1 Structure and union specifiers
...
5 A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted.
...
11 An implementation may allocate any addressable storage unit large enough to hold a bitfield. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.

Short answer: it can, depending on the implementation.

like image 33
John Bode Avatar answered Oct 14 '25 16:10

John Bode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!