Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the size of a class object different based on order of members?

Tags:

c++

class

sizeof

class CHaraICICCC
{
int i;
char c1;
int j;
char c2;
char c3;
char c4;
};

class CHaraIICCCC
{
int i;
int j;
char c1;
char c2;
char c3;
char c4;
};

void fun()
{
    CHaraICICCC eici;
    CHaraIICCCC eiicc;

    int icic = sizeof(eici); // -> output of icic is 16.
    int iicc = sizeof(eiicc); // -> output of icic is 12.
}

If any one knows, Please let me know why like this. Thanks Hara

like image 640
Haranadh Avatar asked Jan 20 '23 20:01

Haranadh


2 Answers

Because of alignment. x86 compilers tend to align int types on 4 bytes boundary (for faster memory access) so CHaraICICCC would probably be laid out as this:

byte  0: \
byte  1: | <--- int i
byte  2: |
byte  3: /  
byte  4: <----- char c1
byte  5: \
byte  6: | <--- Padding (wasted bytes)
byte  7: / 
byte  8: \
byte  9: | <--- int j  
byte 10: |
byte 11: /
byte 12: <----- char c2
byte 13: <----- char c3
byte 14: <----- char c4

for a total of 15 bytes, while CHaraIICCCC would be:

byte  0: \
byte  1: | <--- int i
byte  2: |
byte  3: /  
byte  4: \
byte  5: | <--- int j 
byte  6: |
byte  7: /
byte  8: <----- char c1
byte  9: <----- char c2
byte 10: <----- char c3
byte 11: <----- char c4

for a total of 12 bytes (with no bytes wasted for padding). Of course, this is much compiler-related and dependant on your compilation options.

like image 152
Simone Avatar answered Feb 16 '23 04:02

Simone


Stretching the question of "why" a little, I think I read somewhere that the reason for alignment is that it lets the CPU ignore bits of the data -- if your data is known to be 8-byte aligned, for example, the CPU can just ignore the 3 lower bits of the address, which improves efficiency. I could be wrong, but if I remember correctly, that's why CPUs require or prefer alignment.

like image 39
user541686 Avatar answered Feb 16 '23 04:02

user541686