Why is the size of the class object different in the order of members?

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 anyone knows, please let me know why. thanks hara

+4
source share
3 answers

Due to alignment. X86 compilers tend to align int types on a 4-byte boundary (for faster memory access), so CHaraICICCC will probably be laid out as follows:

 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 

a total of 15 bytes, while CHaraIICCCC will 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 (without bytes wasted to fill). Of course, it depends on the compiler and depends on your compilation options.

+8
source

Stretching the question of โ€œwhyโ€ a bit, I think I read somewhere that the reason for alignment is that it allows the processor to ignore data bits - if your data is known to be 8 byte aligned, for example, the CPU can simply Ignore the 3 least significant bits of the address, which improves efficiency. I could be wrong, but if I remember correctly why processors require or prefer alignment.

+1
source

In package mode, by default on most architectures, members will be aligned with an offset (from the very beginning of the structure) that is a multiple of their size.

If necessary, padding bytes will be added to the structure to get this alignment.

So, assuming the default packaging and 4-byte integers, your first structure really looks like this:

 class CHaraICICCC { int i; char c1; char padding[3]; int j; char c2; char c3; char c4; }; 
0
source

Source: https://habr.com/ru/post/1333768/


All Articles