04. Memory Padding, Struct Alignment & offsetof()

🔴 Difficulty: Advanced | CPU Data Alignment, Padding Bytes, Member Reordering & offsetof()

📖 Definition

Memory alignment is a hardware requirement where CPUs fetch data from memory addresses that are integer multiples of the data type size (e.g. 4-byte int aligns to addresses ending in 0, 4, 8, C). To satisfy alignment, C compilers insert unused padding bytes between struct members. The offsetof(struct_type, member) macro (from <stddef.h>) returns the exact byte offset of a member from the start of the struct.

🎯 Why It Is Used

  • CPU Memory Fetch Speed: Unaligned memory access on modern CPUs requires multiple bus cycles or triggers hardware bus errors. Alignment ensures single-cycle CPU memory loads.
  • Member Reordering Optimization: Ordering struct fields from largest to smallest byte size (e.g., double first, followed by int, then char) minimizes wasted padding bytes.
  • Hardware Network Packet Packing: Disabling padding using compiler attributes (e.g. __attribute__((packed))) for binary wire protocols and hardware register maps.

⚙️ How It Works: Padding Byte Layout Diagram

Consider a struct declared with alternating field types:

struct BadLayout {
    char a;    // 1 byte
    // 3 PADDING BYTES INSERTED HERE (Aligns 'b' to 4-byte boundary)
    int b;     // 4 bytes
    char c;    // 1 byte
    // 3 PADDING BYTES INSERTED AT END (Aligns total struct size to 4-byte multiple)
}; // Total sizeof(struct BadLayout) == 12 bytes! (Only 6 bytes of actual data)

Reordering fields from largest to smallest byte size eliminates internal padding:

struct OptimizedLayout {
    int b;     // 4 bytes
    char a;    // 1 byte
    char c;    // 1 byte
    // 2 PADDING BYTES INSERTED AT END
}; // Total sizeof(struct OptimizedLayout) == 8 bytes! (Saved 4 bytes per instance)

📝 Syntax

#include <stddef.h> // For offsetof() macro

// 1. Inspecting Byte Offset of Member
size_t byte_offset = offsetof(struct_type, member_name);

// 2. GNU C Packed Struct Attribute (Zero Padding)
struct __attribute__((packed)) PackedHeader {
    char flag;
    int payload_id;
}; // sizeof(PackedHeader) == 5 bytes (No padding inserted!)

🔀 Bad vs Optimized Layout Comparison

Layout Strategy Member Declaration Order Total Size (32/64-bit) Wasted Padding
Naive Alternating char, double, char, int 24 Bytes 10 Wasted Bytes
Optimized Reordered double, int, char, char 16 Bytes 2 Wasted Bytes
Packed Attribute __attribute__((packed)) 14 Bytes 0 Wasted Bytes (Slower CPU access)

🌱 Beginner Example: Measuring Real vs Expected Size

#include <stdio.h>

struct Example {
    char c;   // 1 byte
    int i;    // 4 bytes
};

int main(void) {
    printf("Sum of individual field sizes: %zu bytes (1 + 4)\n",
           sizeof(char) + sizeof(int));
    printf("Actual sizeof(struct Example): %zu bytes (Includes padding!)\n",
           sizeof(struct Example));
    return 0;
}

🌼 Intermediate Example: Inspecting Field Offsets with offsetof()

#include <stdio.h>
#include <stddef.h>

struct DataPacket {
    char header_tag; // Byte offset 0
    double timestamp;// Byte offset 8 (7 padding bytes inserted before!)
    int sequence_no; // Byte offset 16
    char status_code;// Byte offset 20
};

int main(void) {
    printf("=== Field Memory Offset Inspection ===\n");
    printf("offsetof(header_tag) : %zu\n", offsetof(struct DataPacket, header_tag));
    printf("offsetof(timestamp)  : %zu\n", offsetof(struct DataPacket, timestamp));
    printf("offsetof(sequence_no) : %zu\n", offsetof(struct DataPacket, sequence_no));
    printf("offsetof(status_code) : %zu\n", offsetof(struct DataPacket, status_code));
    printf("Total Struct Size    : %zu bytes\n", sizeof(struct DataPacket));
    return 0;
}

🌲 Advanced Example: Struct Reordering Optimization Benchmark

#include <stdio.h>

// Wastes 10 bytes on padding
typedef struct {
    char flag1;
    double value1;
    char flag2;
    int count;
} NaiveStruct;

// Reordered by decreasing alignment size
typedef struct {
    double value1; // 8 bytes
    int count;     // 4 bytes
    char flag1;    // 1 byte
    char flag2;    // 1 byte
                   // 2 tail padding bytes
} OptimizedStruct;

int main(void) {
    printf("=== Memory Optimization Results ===\n");
    printf("NaiveStruct Size    : %zu bytes\n", sizeof(NaiveStruct));
    printf("OptimizedStruct Size: %zu bytes\n", sizeof(OptimizedStruct));
    printf("Memory Saved per Item: %zu bytes (%.1f%% reduction!)\n",
           sizeof(NaiveStruct) - sizeof(OptimizedStruct),
           ((double)(sizeof(NaiveStruct) - sizeof(OptimizedStruct)) / sizeof(NaiveStruct)) * 100.0);
    return 0;
}

🔍 Line-by-Line Explanation

  • offsetof(struct DataPacket, timestamp): Calculates byte offset from the start of the struct to timestamp field.
  • double value1; int count; char flag1; char flag2;: Reorders fields by decreasing size to maximize packing density.
  • __attribute__((packed)): Forces the compiler to omit all padding bytes, making struct size equal to the exact sum of member sizes.

💻 Expected Terminal Output

Sum of individual field sizes: 5 bytes (1 + 4)
Actual sizeof(struct Example): 8 bytes (Includes padding!)
=== Field Memory Offset Inspection ===
offsetof(header_tag) : 0
offsetof(timestamp)  : 8
offsetof(sequence_no) : 16
offsetof(status_code) : 20
Total Struct Size    : 24 bytes
=== Memory Optimization Results ===
NaiveStruct Size    : 24 bytes
OptimizedStruct Size: 16 bytes
Memory Saved per Item: 8 bytes (33.3% reduction!)

⚠️ Common Mistakes & Pitfalls

  • Assuming sizeof(struct) Equals Sum of Member Sizes: Expecting sizeof(struct { char a; int b; }) to be 5 bytes instead of 8 bytes causes buffer overrun bugs when serializing to files or sockets.
  • Unaligned Pointer Casts on Packed Structs: Direct pointer access to unaligned members in packed structs can trigger CPU hardware alignment faults on ARM architectures.

📌 Important Rules & Limitations

  • Order struct members from largest data type to smallest data type to minimize padding.
  • Use offsetof() from <stddef.h> to determine exact field byte offsets.

🌐 Multilingual Explanation: English

Compilers insert padding bytes into structs to satisfy CPU alignment requirements. Reorder fields from largest to smallest byte size to optimize memory footprint, and use offsetof() to inspect field byte locations.

🌐 Multilingual Explanation: Hindi (Roman Script)

CPU speed ke liye compiler struct ke andar extra padding bytes add karta hai. Memory bachane ke liye bade data types (jaise double) ko pehle aur chhote data types (jaise char) ko baad mein rakhein.

🌐 Multilingual Explanation: Marathi (Roman Script)

Compilers struct madhye padding bytes taktat. Memory vachvanyasathi mothe data types aadhi liha aani offsetof() vaaparun member offset taspasa.

❓ Practice Questions

  1. Why do compilers insert padding bytes into structures?
  2. How does field order affect the total byte size of a structure?
  3. What header file provides the offsetof() macro?

🚀 Practical Coding Challenge

Write a C program named struct_align_audit.c that defines a struct with 5 fields of different types, uses offsetof() to print the byte offset of each member, and demonstrates field reordering to reduce the total struct size.

🧭 Navigation & Breadcrumbs

← Previous: 03. Arrays & Nested Structs | Module 13 Guide | Next Module: 14. Unions & Bit-Fields →