Structure Padding, Memory Alignment & Dynamic Allocation
“Natural word alignment, member reordering optimization, and heap management.”
1.The Hardware Necessity of Structure Padding
§ 4.1.Modern CPUs access memory in multi-byte words (e.g. 4 bytes on 32-bit systems, 8 bytes on 64-bit systems). If a 4-byte integer begins at an unaligned address (e.g., address 1001), the CPU must perform TWO separate memory read cycles and stitch the bytes together in registers.
To optimize performance, C compilers insert unused filler bytes ('padding') between structure members so that every member begins at an address divisible by its natural size.
Structure Alignment Rules (for a standard 32-bit architecture):
1. Member Alignment: A primitive data type of size k bytes must start at a byte offset that is a multiple of k (char [1 byte]: any offset; short [2 bytes]: multiple of 2; int/float [4 bytes]: multiple of 4; double [8 bytes]: multiple of 4 or 8).
2. Total Structure Alignment: The total size of the structure must be an integer multiple of the LARGEST member's alignment requirement. Trailing padding is added at the end if needed.
2. GATE Worked Numerical: Calculating sizeof(struct)
Don't forget the trailing padding at the end of the structure! The total size must be a multiple of the largest member's size.
Consider the structure on a 32-bit machine where sizeof(char)=1, sizeof(short)=2, sizeof(int)=4:
struct Node {
char a;
int b;
short c;
};
Find sizeof(struct Node).
Step 1: Lay out members sequentially:
- 'char a' takes 1 byte at Offset 0.
- Next member is 'int b' (size 4). It MUST start at an offset divisible by 4.
- Offsets 1, 2, 3 cannot hold 'b'. The compiler inserts 3 padding bytes!
- 'int b' occupies Offsets 4, 5, 6, 7 (4 bytes).
- Next member is 'short c' (size 2). It starts at Offset 8 (8 is divisible by 2).
- 'short c' occupies Offsets 8, 9 (2 bytes).
Step 2: Check total structure size so far:
Offsets 0 to 9 = 10 bytes used.
Step 3: Apply Total Structure Alignment Rule:
Largest member is 'int b' (size 4 bytes).
Total structure size MUST be an integer multiple of 4.
Next multiple of 4 after 10 is 12.
Compiler inserts 2 trailing padding bytes at Offsets 10 and 11.
Final sizeof(struct Node) = 12 bytes.
Primary Academic References & Exam Sources
Every concept in Notes From a B.Tech Brain is synthesized from authoritative academic texts, seminal peer-reviewed research, verified exam archives, and renowned university lectures.
Curated for clarity, rigorous numerical solving, and semester excellence:
Systematic beginner-to-advanced C with clear examples.
Clear step-by-step C explanations — great for semester lab preparation.