I'm learning Cpp from the basics, and when learning structure padding and data alignment, confused with the following:
struct A {
char a;
double b;
char c;
};
struct B
{
char a;
short b;
char c;
};
Using MSVC++ 14.0 32 bit compiler
I understood the concept of data alignment by referring various pages on web.
In the 1st case, the sizeof(A)
will give "24 (1 (a
)+7(padding)+8(b
)+1(c
)+7(struct padding - since double is the max sized variable, padding is used to that value (8-1))".
Here, I understood that because of cache lines (usually 32/64 bytes), double
of 8 byte size is started at a location, which is a multiple of 8 instead of a multiple of 4 (even though compiler is 4 byte long - either case it requires 2 memory cycles but to avoid the data being split across 2 cache line location which is multiple of 8 is chosen)
But in the 2nd case, the sizeof(B)
yields "6 (1(a
) + 1(padding) + 2(b
) + 1(c
) + 1(padding)". This is of course the expected value from the rule (value of x
bytes starts at a location which is multiple of x
). But here, I did not understand why there is a need for b
to start at a location which is multiple of 2
?
Assuming that in struct B
, a
is placed at 0x00
, why can't b
placed at 0x01
and c
at 0x03
?
Even in this case, the value of any of the variables (a
,b
or c
) can be fetched in a single memory cycle (since 4 byte compiler) and this also doesn't result in 2 cache lines. I didn't understand the use of padding in this case.
Please help!!! I'm just curious to know, what advantage padding adds here?