Python Memory Word Alignment & Struct Padding
CPUs fetch memory in 4-byte or 8-byte word boundaries for hardware efficiency. The compiler automatically inserts invisible padding bytes into structs to align fields with their natural boundaries. Ordering struct fields from largest to smallest minimizes padding overhead.
"Packing a suitcase: if you place bulky boots (8-byte ints) at the bottom and small socks (1-byte chars) in the gaps, everything fits tightly without wasted empty air pockets."
Deep Dive: How It Works
Natural Alignment: A 4-byte int is aligned on addresses divisible by 4.
Padding Insertion: Compilers insert 1 to 3 bytes between smaller and larger fields.
Field Reordering: Placing largest data types first minimizes wasted padding bytes.
Syntax Blueprint
struct Optimized {
int id; // 4 bytes
char flagA; // 1 byte
char flagB; // 1 byte + 2 bytes padding
};Ordering largest primitives first reduces struct padding and memory footprints.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Assuming sizeof(struct) is simply the sum of its individual member sizes.Why it happens: Hardware word alignment adds invisible padding bytes.
How to fix: Always use sizeof(struct Type) rather than manual arithmetic calculation.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Confirm Optimal Alignment
Print "Optimal Alignment: TRUE\n" after packet size output.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.