How do structure alignment and memory padding work in C language?
Memory Alignment Principles:
-
Alignment Rules
- Structure members align to their natural boundaries
- char: 1-byte alignment
- short: 2-byte alignment
- int: 4-byte alignment
- double: 8-byte alignment (64-bit systems)
-
Structure Total Size
- Must be a multiple of its largest member size
- May require padding bytes at the end
Example Analysis:
cstruct Example1 { char c; // 1 byte + 3 bytes padding int i; // 4 bytes }; // Total size: 8 bytes struct Example2 { char c1; // 1 byte + 1 byte padding short s; // 2 bytes int i; // 4 bytes }; // Total size: 8 bytes struct Example3 { char c1; // 1 byte + 7 bytes padding double d; // 8 bytes char c2; // 1 byte + 7 bytes padding }; // Total size: 24 bytes
Optimization Techniques:
-
Member Ordering Optimization
- Arrange members in descending size order
- Reduce padding byte waste
-
Using Compiler Directives
c#pragma pack(1) // 1-byte alignment struct Packed { char c; int i; }; #pragma pack() // Restore default alignment -
Bit Field Usage
cstruct BitField { unsigned int a : 3; // 3 bits unsigned int b : 5; // 5 bits };
Important Notes:
- Alignment rules may vary across platforms
- Excessive packing can affect access performance
- Consider byte order and alignment for network transmission