Calculate Struct Size With Alignment Padding and Reorder Fields
Last updated: November 29, 2026
Quick Overview
Given a list of C struct fields with sizes and alignment requirements, compute the struct's size including padding and find a field order that minimizes it, as you would when shrinking a hot record in a C++ service.
0
0
0 solved
Given a list of C struct fields with sizes and alignment requirements, compute the struct's size including padding and find a field order that minimizes it, as you would when shrinking a hot record in a C++ service.
Google's C++ servers keep billions of small records in memory (index entries, cache metadata), and a few bytes of padding per record add up to real RAM cost. This screen question checks that you understand alignment rules and can reason about layout without a compiler.
What the Interviewer Expects
- Explain why fields must start at multiples of their alignment
- Add trailing padding so arrays of the struct stay aligned
- Compute total size by simulating the layout
- Show that sorting by alignment descending minimizes padding
- Relate the savings to fleet-scale memory
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- Why might reordering fields hurt performance even though it saves memory?
- What does `#pragma pack(1)` do and what does it cost?
- How would bit fields or a separate hot/cold split help further?
- How does `alignas(64)` relate to false sharing?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
- Input: list of
(name, size, align)such as('flag', 1, 1),('id', 8, 8). layout(fields)returns(total_size, offsets)following C rules: each field starts at the next multiple of its ali...
High-Level Design
Take {bool a; int64 b; bool c; int32 d;}. a at 0, b must start at 8 (7 bytes padding), c at 16, d at 20, end at 24, already a multiple of 8, so 24 bytes for 14 bytes of data. Sorted by align...