Question

Let's say we have:

struct A{
    char a1;
    char a2;
};

struct B{
    int b1;
    char b2;
};

struct C{
    char C1;
    int C2;
};

I know that because of padding to a multiple of the word size (assuming word size=4), sizeof(C)==8 although sizeof(char)==1 and sizeof(int)==4.

I would expect that sizeof(B)==5 instead of sizeof(B)==8.

But if sizeof(B)==8 I would expect that sizeof(A)==4 instead of sizeof(A)==2.

Could anyone please explain why the padding and the aligning are working differently in those cases?

Was it helpful?

Solution

A common padding scheme is to pad structs so that each member starts at an even multiple of the size of that member or to the machine word size (whichever is smaller). The entire struct is padded following the same rule.

Assuming such a padding scheme I would expect:

The biggest member in struct A has size 1, so no padding is used.

In struct B, the size of 5 is padded to 8, because one member has size 4. The layout would be:

int     4
char    1
padding 3

In struct C, some padding is inserted before the int, so that it starts at an address divisible by 4.

The layout would be:

char    1
padding 3
int     4

OTHER TIPS

It's up to the compiler to decide how best to pad the struct. For some reason, it decided that in struct B that char b2 was more optimally aligned on a 4 byte boundary. Additionally, the specific architecture may have requirements/behaviors that the compiler takes into account when deciding how to pad structs.

If you 'pack' the struct, then you'd see the sizes you expect (although that is not portable and may have performance penalties and other issues depending on the architecture).

structs in general will be aligned to boundaries based on the largest type contained. Consider an array of struct B myarray[5];

struct B must be aligned to 8 bytes so that it's b1 member is always on a 4 byte boundary. myarray[1].b1 can't start at the 6th byte into the array, which is what you would have if sizeof(B) == 5.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top