Structure size optimization in C

Did you ever noticed the order of members in the data structures affects the whole size of the structure in C language? For example, if you define this T1 structure:

typedef struct {
char a; /* 1 byte */
int b; /* 4 bytes */
char c; /* 1 byte */
} T1;

The sizeof(T1) will give you 12 bytes. But if you reorder the structure members like this:

typedef struct {
int b; /* 4 bytes */
char a; /* 1 byte */
char c; /* 1 byte */
} T2;

It will be only 8 bytes long! The short answer is because of data alignment and padding. See the difference:c_structures_padding

typedef struct {
char a; /* 1 byte */
pad[3]; /* 3 bytes padding */
int b; /* 4 bytes */
char c; /* 1 byte */
pad[3]; /* 3 bytes padding */
} T1;

typedef struct {
int b; /* 4 bytes */
char a; /* 1 byte */
char c; /* 1 byte */
pad[2]; /* 2 bytes padding */
} T2;

For the long one read the brilliant “The Lost Art of C Structure Packing” essay by Eric S. Raymond and you will also learn the meaning of the “slop” term.

Advertisements

About mezzantrop

10 years of experience in large SAN and storage environments: mainly Hitachi, HP and Brocade. Now I am a proud SAN/storage IBMer. Empty – expect-like tool author. FreeBSD enthusiast.
This entry was posted in Impressions and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s