Sunday 2 February 2014

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

This is because of structure alignment. Structure alignment refers to the ability of the compiler to insert unused memory into a structure so that data members are optimally aligned for better performance. Many processors perform best when fundamental data types are stored at byte-addresses that are multiples of their sizes.
Here's an example using typical settings for an x86 processor:
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(X); /* = 12 */
const int sizeY = sizeof(Y); /* = 8 */
const int sizeZ = sizeof(Z); /* = 8 */
One can minimize the size of structures by putting the largest data types at the beginning of the structure and the smallest data types at the end of the structure (like structure Z in the example above).
IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special #pragma statements to change the structure alignment settings.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More