![]() |
VOOZH | about |
In C++, a structure (struct) is a user-defined data type that allows grouping variables of different types under a single name. When we define a structure, the compiler may insert extra bytes between the members to ensure proper alignment. This process is called structure padding.
Example:
Size of struct: 12
In the above program, expected size of the structure Example is:
So, the size should be 6 bytes. But the size came out to be 12 bytes. This is due to structure padding as shown:
Most processors access data faster when variables are aligned on memory addresses that are multiples of their size (or alignment requirements). To achieve this, the compiler may pad the structure so that members are placed at appropriate offsets.
It provides the following advantages
Structure padding makes access fast but takes unnecessary extra space, but we can follow some techniques to reduce the structure padding:
By ordering members by size, where the larger members come first (decreasing order), we can minimize the structure padding. For example, if we arrange the above Example structure in this way, the padding can be reduced:
Size of struct: 8
C++ also provide an option to disable structure padding. It is possible using #pragma pack directive or using alignas.
Size of struct: 6 Size of struct: 6