3 ms·
Why is the natural alignment of structs equal to the size of their largest member?
by branko_d 2y ago
Why is the natural alignment of structs equal to the size of their largest member?
- kllrnohj 2y agoTo ensure that member is itself still aligned properly in "global space". The start of the struct is assumed to be universally aligned (malloc, etc.. make that a requirement in fact) or aligned for the requirements of the struct itself (eg, array). Thus any offset into the struct only needs to be aligned to the requirements of the largest type. https://www.kernel.org/doc/html/latest/core-api/unaligned-memory-access.html https://www.kernel.org/doc/html/latest/core-api/unaligned-me... has a lot more general context on alignment and why it's important
- jcranmer 2y agoIt's not. It's equal the maximum alignment of their members. For primitive types (like integers, floating-point types and pointers), size == alignment on most machines nowadays (although on 32-bit machines, it can be a toss-up whether a 64-bit integer is 64-bit aligned or 32-bit aligned), so it can look like it's based on size though.