Structure Padding in C
Structure padding is a technique used by the compiler to align the data members of a structure in memory according to the architecture’s word size.
It helps the CPU access memory efficiently and can result in unused memory between structure members.
1. Why Structure Padding Occurs
• CPU accesses memory faster at aligned addresses (usually multiples of 2, 4, or 8 bytes depending on system architecture).
• To maintain alignment, the compiler adds extra bytes (padding) between structure members.
• Padding also occurs at the end of the structure to make the total size a multiple of the largest member's size.
2. Example of Structure Padding
Consider a structure with members of different sizes:
#include <stdio.h>
struct Example {
char c; // 1 byte
int i; // 4 bytes
char d; // 1 byte
};
int main() {
struct Example e;
printf("Size of structure = %zu\n", sizeof(e));
return 0;
}
Output on a 32-bit or 64-bit system might be: Size of structure = 12 bytes
Explanation: The compiler adds padding after 'c' (3 bytes) and after 'd' (3 bytes) to align 'int' and overall structure to 4-byte boundaries.
3. How to Create a Structure
Creating a structure with padding is straightforward; the compiler automatically adds padding based on data member alignment.
Example without explicitly controlling padding:
struct Student {
char grade;
int roll;
float marks;
};
The compiler may add padding after 'grade' to align 'int' and 'float' properly.
4. Controlling Structure Padding
In some compilers, you can control or remove padding using compiler-specific directives or pragmas.
Example in GCC using __attribute__((packed)):
struct __attribute__((packed)) PackedExample {
char c;
int i;
char d;
};
int main() {
printf("Size of packed structure = %zu\n", sizeof(struct PackedExample));
return 0;
}
Now the size may be 6 bytes instead of 12, but accessing members may be slower or unaligned on some systems.
5. Advantages and Disadvantages
Advantages:
Efficient CPU memory access due to alignment.
Consistency across architectures for padding and alignment.
Disadvantages:
Wastes memory due to added padding.
Manual packing can lead to slower memory access and possible alignment faults on some architectures.
Conclusion
Structure padding is automatically applied by the compiler to align data members for efficient CPU access.
By understanding padding, you can optimize memory usage, control structure size using packed attributes, and write efficient C programs.
Codecrown