Why isn\'t sizeof for a struct equal to the sum of sizeof of each member?

Answer

This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs:

  • Mis-aligned access might be a hard error (often SIGBUS).
  • Mis-aligned access might be a soft error.
    • Either corrected in hardware, for a modest performance-degradation.
    • Or corrected by emulation in software, for a severe performance-degradation.
    • In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors.

Here's an example using typical settings for an x86 processor (all used 32 and 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 */};constint sizeX =sizeof(X);/* = 12 */constint sizeY =sizeof(Y);/* = 8 */constint sizeZ =sizeof(Z);/* = 8 */

One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure Z in the example above).

All c++ Questions

Ask your interview questions on c

Write Your comment or Questions if you want the answers on c from c Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---