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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With