Project 2: Struct Layout Analyzer

A C program that defines several structs with identical members but different orderings. The program will then print the sizeof each struct and the memory offset of each member using the offsetof macro, visually demonstrating the impact of padding.

Quick Reference

Attribute Value
Primary Language C
Alternative Languages C++, Rust
Difficulty Level 1: Beginner
Time Estimate Weekend
Knowledge Area Memory Layout / Data Structures
Tooling GCC/Clang
Prerequisites Basic C knowledge of structs.

What You Will Build

A C program that defines several structs with identical members but different orderings. The program will then print the sizeof each struct and the memory offset of each member using the offsetof macro, visually demonstrating the impact of padding.

Why It Matters

This project builds core skills that appear repeatedly in real-world systems and tooling.

Core Challenges

  • Defining multiple struct variations → maps to organizing your code for comparison
  • Using sizeof correctly → maps to understanding object size
  • Using the offsetof macro → maps to inspecting internal struct layout
  • Printing a visual representation → maps to making the padding visible and understandable

Key Concepts

  • Struct Padding and Alignment: “Effective C” Ch. 2 - Robert C. Seacord
  • offsetof macro: C standard library documentation (stddef.h)
  • Data Primitives Sizes: “The C Programming Language” Ch. 2 - K&R

Real-World Outcome

$ ./struct_analyzer

Analyzing 'struct unoptimized':
  Total size: 24 bytes (8 bytes wasted)
  Layout:
    [ 0] char    c   (1 byte)
    [ 1] --- padding --- (7 bytes)
    [ 8] double  d   (8 bytes)
    [16] int     i   (4 bytes)
    [20] --- padding --- (4 bytes)

Analyzing 'struct optimized':
  Total size: 16 bytes (0 bytes wasted)
  Layout:
    [ 0] double  d   (8 bytes)
    [ 8] int     i   (4 bytes)
    [12] char    c   (1 byte)
    [13] --- padding --- (3 bytes)

Implementation Guide

  1. Reproduce the simplest happy-path scenario.
  2. Build the smallest working version of the core feature.
  3. Add input validation and error handling.
  4. Add instrumentation/logging to confirm behavior.
  5. Refactor into clean modules with tests.

Milestones

  • Milestone 1: Minimal working program that runs end-to-end.
  • Milestone 2: Correct outputs for typical inputs.
  • Milestone 3: Robust handling of edge cases.
  • Milestone 4: Clean structure and documented usage.

Validation Checklist

  • Output matches the real-world outcome example
  • Handles invalid inputs safely
  • Provides clear errors and exit codes
  • Repeatable results across runs

References

  • Main guide: LEARN_C_PERFORMANCE_DEEP_DIVE.md
  • “The C Programming Language” by Brian W. Kernighan and Dennis M. Ritchie