Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are unpacked struct in packed struct automatically packed?

Are unpacked struct in packed struct automatically packed by GCC?

In other words, do __packed__ attribute automatically propagates to nested structures?

That is to say:

struct unpackedStruct{
    int16_t field1;
    int32_t field2;
    // etc...
}

struct packedStruct{
    int16_t field1;
    struct unpackedStruct struct1; // <-- Is this struct packed?
    // etc...
} __attribute__((__packed__));
like image 938
quent Avatar asked Feb 26 '21 15:02

quent


Video Answer


1 Answers

No, the inner structure is not packed. In this Godbolt example, we can see that struct foo is not packed inside struct bar, which has the packed attribute; the struct bar object created contains three bytes of padding (visible as .zero 3) inside its struct foo member, between the struct foo members c and i.

Current documentation for GCC 10.2 explicitly says the internal layout of a member of a packed structure is not packed (because of the attribute on the outer structure; it could be packed due to its own definition, of course).

(In older documentation that said that applying packed to a structure is equivalent to applying it to its members, it meant the effect of applying packed to the “variable” that is the member, described in the documentation for variable attributes. When packed is applied to a structure member, it causes the member’s alignment requirement to be one byte. That is, it eliminates padding between previous members and that member, because no padding is needed to make it aligned. It does not alter the representation of the member itself. If that member is an unpacked structure, it remains, internally, an unpacked structure.)

like image 82
Eric Postpischil Avatar answered Oct 20 '22 00:10

Eric Postpischil