Is gcc's __attribute__((packed)) / #pragma pack unsafe?

前端 未结 5 1248
广开言路
广开言路 2020-11-22 03:48

In C, the compiler will lay out members of a struct in the order in which they\'re declared, with possible padding bytes inserted between members, or after the last member,

5条回答
  •  渐次进展
    2020-11-22 04:18

    It's perfectly safe as long as you always access the values through the struct via the . (dot) or -> notation.

    What's not safe is taking the pointer of unaligned data and then accessing it without taking that into account.

    Also, even though each item in the struct is known to be unaligned, it's known to be unaligned in a particular way, so the struct as a whole must be aligned as the compiler expects or there'll be trouble (on some platforms, or in future if a new way is invented to optimise unaligned accesses).

提交回复
热议问题