c - Why should a struct's size reflect its alignment? -
according wikipedia:
the last member padded number of bytes required total size of structure should multiple of largest alignment of structure member
in understanding, means in following:
struct { char *p; // 8 bytes char c; // 1 byte }; struct b { struct a; // 16 bytes char d; // 1 bytes };
struct a
have size of 16 bytes, , struct b
have size of 24 bytes.
the common explanation arrays of a
should have elements accessible @ address of array plus index times size of a
.
but fail see why case. why not a
has size 9 , b
has size 10 (both 8 bytes alignment), , use special "array-storage" size when indexing array?
of course, we'd still store types in arrays in way compatible alignment (using 16 bytes store each b
element). then, we'd compute element addresses taking account alignment, instead of considering size alone (the compiler can statically).
for example, store 64 objects in 1kb bytes array of b
's, instead of 42.
in each translation unit of c, sizeof(t)
same, regardless of context of t
. proposal introduce @ least 2 values sizeof(t)
: 1 arrays of t
, different 1 individual objects of t
. introduces context-dependence sizeof
operator. incompatible how c handles pointers, arrays, , addresses of objects.
consider following:
void zero_a(struct *a) { memset(a,0,sizeof(*a)); } /* ... */ struct single; struct several[3]; struct b b; b.d = 3; zero_a(&b.a); zero_a(&single); zero_a(several+1);
under proposal, zero_a
have know whether pointer passed pointed struct a
in array context (where sizeof(*a) == 16
) or struct a
outside of array context (where sizeof(*a) == 9
). standard c doesn't support this. if compiler guessed wrong, or information lost (eg: in round-trip through volatile struct *
), zero_a(&single)
invoke undefined behavior (by writing past bounds of single
), , zero_a(&b.a)
overwrite b.d
, invoke undefined behavior.
tightly packing structs array relatively uncommon requirement, , adding context-dependence sizeof
introduce lot of complications language, libraries, , abis. there times need this, , c gives tools need: memcpy
, unions.
Comments
Post a Comment