c++ - Why isn't sizeof for a struct equal to the sum of sizeof of each member? -
why 'sizeof' operator return size larger structure total sizes of structure's members?
this because of padding added satisfy alignment constraints. data structure alignment impacts both performance , correctness of programs:
- mis-aligned access might hard error (often
sigbus
). - mis-aligned access might soft error.
- either corrected in hardware, modest performance-degradation.
- or corrected emulation in software, severe performance-degradation.
- in addition, atomicity , other concurrency-guarantees might broken, leading subtle errors.
here's example using typical settings x86 processor (all used 32 , 64 bit modes):
struct x { short s; /* 2 bytes */ /* 2 padding bytes */ int i; /* 4 bytes */ char c; /* 1 byte */ /* 3 padding bytes */ }; struct y { int i; /* 4 bytes */ char c; /* 1 byte */ /* 1 padding byte */ short s; /* 2 bytes */ }; struct z { int i; /* 4 bytes */ short s; /* 2 bytes */ char c; /* 1 byte */ /* 1 padding byte */ }; const int sizex = sizeof(struct x); /* = 12 */ const int sizey = sizeof(struct y); /* = 8 */ const int sizez = sizeof(struct z); /* = 8 */
one can minimize size of structures sorting members alignment (sorting size suffices in basic types) (like structure z
in example above).
important note: both c , c++ standards state structure alignment implementation-defined. therefore each compiler may choose align data differently, resulting in different , incompatible data layouts. reason, when dealing libraries used different compilers, important understand how compilers align data. compilers have command-line settings and/or special #pragma
statements change structure alignment settings.
Comments
Post a Comment