Coding/Learn/c/c struct padding and alignment
C Foundational Course
01.Introduction, Compilation Pipeline & Syntax
02.Variables, Primitives & Explicit Type Casting
03.Operators, Precedence & Booleans (<stdbool.h>)
04.Control Flow: If-Else, Ternary & Switch
05.Loops (For, While, Do-While) & Jump Statements
06.Contiguous Arrays & Multi-Dimensional Matrices
07.Null-Terminated Strings & <string.h>
08.User Input, scanf & fgets Buffer Safety
09.Pointers, Memory Addresses & Dereferencing
10.Functions, Prototypes & Pass-by-Pointer
11.11. Recursion & High-Speed Function Pointers
12.File Streams: Create, Write & Read (fopen/fclose)
13.Structures, Unions & typedef Aliasing
14.Memory Word Alignment & Struct Padding
15.Enums & Bitwise Manipulation (Flags & Masks)
16.Dynamic Memory: malloc, calloc, realloc & free
17.Defensive Error Handling, errno & Assertions
18.Preprocessor Macros & Storage Classes
19.Fixed-Width Types (stdint.h), Math & Time (<time.h>)
20.Capstone: High-Performance In-Memory Key-Value Engine
Course Certificate0%

Complete all lessons to earn

LearnMemory Word Alignment & Struct Padding
14 / 20 0%
Lesson 14 of 20
6 mins read

Memory Word Alignment & Struct Padding

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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.

PointCore Rules to Remember

Point star
Cache Line Density: Optimized structs pack more elements per 64-byte L1/L2 CPU cache line.
Point star
sizeof Reflection: sizeof(struct Packet) includes compiler padding bytes.
Point star
Binary Protocols: Packed structs are critical when serializing raw packets over network sockets.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Order struct fields in descending order of size (8B doubles -> 4B ints -> 2B shorts -> 1B chars) to guarantee minimal padding.

Live Interactive Example

Hit Run Code to see it live
Packet Struct Size Inspection
C11 / GCC 9.2
1
2
3
4
5
6
7
8
9
10
11
12
13
Output Console
Click "Run Code" to view the rendered output.
How it works: 4 bytes for packetId + 1 byte for flagA + 1 byte for flagB + 2 padding bytes = 8 bytes total.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Confirm Optimal Alignment

  • PointPrint "Optimal Alignment: TRUE\n" after packet size output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates