Structure Size and Memory Alignment

Though it’s possible to guess the byte size of a structure, it’s bad practice to do so. Even advanced C programmers, who know variable widths by heart, rely upon the sizeof operator to obtain a structure’s size.

First, if your code is portable, it might not always run on a machine that allocates, say, 4 bytes to an int variable. When I first learned to program, an int was 2-bytes wide. In the future, who knows?

Second, if you eyeball the structure members and come up with 52 bytes as the structure size, you’re effectively creating a constant. What if you modify the structure? Then you must hunt down the proper instances of “52” in the code and replace them with the new value. That’s really dumb and I don’t see anyone actually doing such a thing.

Third, sometimes the size of a structure is difficult to predict because of memory alignment, which describes how variables are stored in memory. For a structure, memory alignment may place gaps between the structure members. The effect is that the overall size of the structure is different from what you calculate in your head.

In the following code, the person structure has three members. The two string members have sizes of 21 and 20 bytes. The int member occupies 4 bytes. In your head, you could calculate that the structure gobbles 45 bytes of storage. Are you correct?

#include <stdio.h>

int main()
{
    struct person {
        char first_name[21];
        char last_name[20];
        int age;
    };

    printf("The structure 'person' has a size %lu\n",sizeof(struct person));

    return(0);
}

Here’s sample output:

The structure 'person' has a size 48

According to the sizeof operator, the size of the structure is 48 bytes, not the 45 bytes I eyeballed. The extra three bytes are sandwiched between members first_name and last_name. It’s padding added when the structure is assigned an address.

Why the padding? Why are variables stored with memory alignment?

The alignment ensures that the processor can efficiently access the member. Without it, extra overhead is required to access variables at oddball memory locations. And the alignment can be unpredictable, which is why it’s always best to use the sizeof operator to return a structure’s size in memory.

Leave a Reply