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:
C++
#include <iostream>
using namespace std;
struct Example {
char c; // 1 byte
int i; // 4 bytes
char d; // 1 byte
};
int main() {
Example ex;
cout << "Size of struct: " << sizeof(ex) << endl;
return 0;
}
In the above program, expected size of the structure Example is:
- char c - 1 byte
- int i - 4 bytes
- char d - 1 byte
So, the size should be 6 bytes. But the size came out to be 12 bytes. This is due to structure padding as shown:
- char c - 1 byte
- 3 bytes padding - to align int i on a 4-byte boundary
- int i - 4 bytes
- char d - 1 byte
- 3 bytes padding - to make the total size a multiple of the largest alignment (4 bytes)
Why Does Structure Padding Occur?
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
- Aligned data can be fetched in fewer CPU cycles.
- Many architectures require data to be aligned on certain boundaries (e.g., 4-byte alignment for int on 32-bit systems).
- Reduces the chance of hardware faults on platforms that don’t support unaligned access.
How to Minimize Padding?
Structure padding makes access fast but takes unnecessary extra space, but we can follow some techniques to reduce the structure padding:
Order Members by Size
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:
C++
#include <iostream>
using namespace std;
struct Example {
int i; // 4 bytes
char c; // 1 byte
char d; // 1 byte
};
int main() {
Example ex;
cout << "Size of struct: " << sizeof(ex) << endl;
return 0;
}
Use #pragma pack (compiler-specific) or alignas
C++ also provide an option to disable structure padding. It is possible using #pragma pack directive or using alignas.
C++
#include <iostream>
using namespace std;
// Force 1-byte packing (may hurt performance)
#pragma pack(1)
struct Example2 {
char c;
int i;
char d;
};
// Or
struct alignas(1) Example1 {
char c;
int i;
char d;
};
int main() {
cout << "Size of struct: "<< sizeof(Example1)
<< endl;
cout << "Size of struct: " << sizeof(Example2);
return 0;
}
OutputSize of struct: 6
Size of struct: 6