I have a structure
struct abc{
int32_t status;
union A;
};
sizeof(int32_t) is 4. sizeof(union A) is 24.
I was expecting that status
should get aligned and take total 8 bytes (considering 64 bit compiler) but the size of structure abc is coming as 28 and not 32. Can someone explain why ? Note it is not pragma packed.
union A{
int8_t a;
struct b;
struct c;
}
struct b
{
int8_t a;
int32_t b2;
int32_t b3;
int32_t b4;
}
struct c
{
struct b;
int32_t c1;
int32_t c2;
}
CodePudding user response:
The largest field in any substructure is 4 bytes in size, so the structures will have 4 byte alignment.
Going from the bottom up, the largest field in struct b
is a int32_t
, so struct b
has 4 byte alignment.
struct c
contains int32_t
which is 4 bytes and struct b
which has 4 byte alignment, so struct c
has 4 byte alignment.
union A
has a uint8_t
which has 1 byte alignment, struct b
which has 4 byte alignment, and struct c
which has 4 byte alignment, so union A
has 4 byte alignment.
Finally, struct abc
has a int32_t
which is 4 bytes and union A
which has 4 byte alignment, so struct abc
has 4 byte alignment.