In C/C++ you can define structs for your data. Sometimes it could be a little bit confusing how much memory they’ll allocate, if you don’t know what’s happening behind the scene.

Here is a simple struct:

struct example {
    char c1;  // 1 Byte
    short s1; // 2 Bytes
    char c2;  // 1 Byte
    long l1;  // 4 Bytes
    char c3;  // 1 Byte
}; // 9 Bytes ??

cout << sizeof(example); // 16 Bytes !!!

Hmm…. why does this struct allocate 16 Bytes when the data types in it should only require 9 Bytes?

Members of a structure must appear at the correct byte boundaries. While char variables can be aligned at any byte boundary, shorts can only be addressed at even byte boundaries, and longs only at every 4th byte.

Because of this the compiler automatically adds padding bytes to the structure, so that the members appear at the correct memory location. In our example the compiler adds one padding byte after the c1-member, three padding bytes after the c2-member and fills in the remaining bytes after the c3-member.

You can insert padding-members so you can see how much memory a struct will require, just by looking at your source:

struct example {
    char c1;           // 1 Byte
    char _padding1;    // 1 Padding-Byte
    short s1;          // 2 Bytes
    char c2;           // 1 Byte
    char _padding2[3]; // 3 Padding-Bytes
    long l1;           // 4 Bytes
    char c3;           // 1 Byte
    char _padding3[3]; // 3 Padding-Bytes

cout << sizeof(example); // 16 Bytes !!!

Now it’s quite obvious that we’re wasting bytes. So let’s rearrange the struct a little bit:

struct example {
    long l1;         // 4 Byte 
    short s1;        // 2 Byte 
    short _padding1; // 2 Bytes
    char c1;         // 1 Byte
    char c2;         // 1 Byte
    char c3;         // 1 Byte
    char _padding2;  // 2 Bytes

cout << sizeof(example); // 12 Bytes (yeah, we saved 4 bytes)

Now our struct allocates 12 Bytes instead of 16. Cool, eh!?

Usually, you don’t need to put in the padding members in the struct, as the compiler will take care of it. But if you are used to do it, and you have to add additional members later on it’s more easy for you to put them at the correct location. In our example you can add three additional chars to the struct and it still only requires 12 Bytes.

  1. rride (2011-01-22 23:11)

    Have you seen this utility for reducing padding size in data structures? It’s a really cool one=)

  2. joe (2011-02-17 07:22)

    thanks for the tip

Add your comment now