Structure Padding in C
Structure padding is extra unused bytes added by the compiler between structure members (or after the last member) to align them according to the CPU's memory access requirements.
Modern processors read/write data faster when it is properly aligned in memory (usually at addresses that are multiples of 2, 4, 8 bytes, depending on data type).
• Improves performance (faster memory access)
• Increases memory consumption
• Not part of the data – purely compiler optimization
• Increases memory consumption
• Not part of the data – purely compiler optimization
1. Why Does Padding Occur? (Alignment Rules)
Each data type has its natural alignment requirement (typically equal to its size):
| Data Type | Size (bytes) | Typical Alignment |
|---|---|---|
| char | 1 | 1 byte |
| short | 2 | 2 bytes |
| int / float | 4 | 4 bytes |
| double / long long | 8 | 8 bytes |
| pointers (most systems) | 4 or 8 | 4 or 8 bytes |
Note: Compiler adds padding bytes so that each member starts at an address that is a multiple of its alignment requirement.
2. Classic Example of Structure Padding
C
Padding between members
#include <stdio.h>
struct Example1 {
char a; // 1 byte
int b; // 4 bytes
char c; // 1 byte
};
int main() {
printf("Size of struct Example1: %zu bytes\n", sizeof(struct Example1));
// Output: 12 bytes (not 6)
return 0;
}
3. Another Common Real-World Example
C
Student record structure
struct Student {
char name[20]; // 20 bytes
int roll; // 4 bytes
char grade; // 1 byte
double gpa; // 8 bytes
};
// Size = ? (usually 40 bytes on 64-bit system)
4. How to Avoid / Control Structure Padding
- Reorder members (largest to smallest size) – most effective & portable
- Use #pragma pack (compiler-specific)
- Use __attribute__((packed)) – GCC/Clang
- Use #pragma pack(1) / push/pop for selective control
C
Reducing padding by reordering + packed example
// Reordered (better) - usually 33 bytes
struct StudentOptimized {
double gpa;
int roll;
char name[20];
char grade;
};
// Packed (no padding) - 33 bytes
#pragma pack(1)
struct StudentPacked {
char name[20];
int roll;
char grade;
double gpa;
};
#pragma pack() // reset
5. When to Use Packed Structures?
- Network programming (fixed packet formats)
- Hardware registers / embedded systems
- File formats / serialization (binary files)
- Interfacing with legacy systems
- Memory-critical applications
Codecrown