Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C++ make the structure tighter?

Tags:

c++

packing

For example, I have a class,

 class naive { public:     char a;     long long b;     char c;     int d; }; 

and according to my testing program, a to d are built one after another, like

 a------- bbbbbbbb c---dddd 

- means unused.

Why does not C++ make it tighter, like

 ac--dddd bbbbbbbb 
like image 395
Dante May Code Avatar asked Jul 18 '11 09:07

Dante May Code


People also ask

Why is structure padding done in C?

Structure Padding in C: The structure padding is automatically done by the compiler to make sure all its members are byte aligned. Here 'char' is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary. For 'int' and 'double', it takes up 4 and 8 bytes respectively.

What is structure packing in C?

Structure padding is a concept in C that adds the one or more empty bytes between the memory addresses to align the data in memory.

How many bits are padded between C and D?

c and d are one byte and thus aligned no matter where you put them for the single-byte CPU instructions. The int however needs to be aligned on a 4-byte boundary, which to get there requires two bytes of padding after d. This gets you to 8. It seems like most compilers would align members in the same way.


1 Answers

Class and struct members are required by the standard to be stored in memory in the same order in which they are declared. So in your example, it wouldn't be possible for d to appear before b.

Also, most architectures prefer that multi-byte types are aligned on 4- or 8-byte boundaries. So all the compiler can do is leave empty padding bytes between the class members.

You can minimize padding by reordering the members yourself, in increasing or decreasing size order. Or your compiler might have a #pragma pack option or something similar, which will seek to minimize padding at the possible expense of performance and code size. Read the docs for your compiler.

like image 113
Graham Borland Avatar answered Sep 19 '22 15:09

Graham Borland