Question

Consider the following code segment:

struct MixedData {
    char a;
    short b;
    char c;
    long d;
    char e;
};

int main() {
    cout<<sizeof(MixedData)<<endl;
}

(Ignore the C++ syntax, since it is not the issue here)
The output for this code is 24, and I don't quite understand why.
I'll denote:
C: char
S: short
L: long
P: compiler padding
and each | | is one byte.
to my best understanding, the data alignment is:

|C|P|S|S|C|P|P|P|L|L|L|L|L|L|L|L|C|P|P|P|

so the output should be 20, shouldn't it? the funny thing is that when MixedData becomes:

struct MixedData {
    char a;
    short b;
    char c;
    int d;
    char e;
};

the size becomes 16, as it should.
Does anyone have an explanation for that?

Was it helpful?

Solution

If your "long" is 8 bytes, what's going to happen is:

C P S S C P P P L L L L L L L L C P P P P P P P P

The last 4 padding bytes bring the total struct size to a multiple of 8 bytes.

If you are wondering why this is, it is because you want the access to each struct member to be aligned. Your platform is clearly 64 bit (8 byte). If we didn't have the last 4 padding bytes, an array of structs would be:

C P S S C P P P L L L L L L L L C P P P | C P S S C P P P L L L L L L L L C P P P | ...

Note that the second long value is split between 2 different 8 byte blocks! It is at offset 28 from the start of the array, and 8 byte blocks start at 24 and 32...

For the same reason, char a; long b; will be 16 bytes - the char will be padded to 8 bytes to keep the long at an 8 byte boundary.

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