KatInterview

Struct Layout and Binary Compatibility in C++

System DesignModel answer
HardModel answerSystem Designcppmemory-layoutalignment

Last updated

Explain how alignment and padding determine object size and layout in C++, and why the C++ ABI breaks easily across toolchains, with practical strategies for keeping binary interfaces stable.

You are preparing for a senior C++ or systems-programming conversation. Two linked fundamentals topics come up, and you are expected to answer both with low-level precision and an eye for practical trade-offs.

Part 1: How objects are laid out in memory

  • Explain what alignment means in C and C++, and how alignof relates to where an object may live.
  • Describe padding, both between members and at the end of a struct or class.
  • Use a short example to show that reordering data members can change sizeof.
  • Discuss why alignment exists (hardware and performance reasons) and what can go wrong because of it: surprising sizes, trouble with binary data, and undefined behavior from misaligned access.
  • Describe how a developer can inspect or deliberately control layout, and what risks come with overriding the defaults.

Part 2: Binary interfaces

  • Define an Application Binary Interface (ABI) and contrast it with a source-level API.
  • List what an ABI typically fixes: calling conventions, data layout, name mangling, exception handling, virtual table layout, and so on.
  • Explain why the C++ ABI tends to break between compilers, or between versions of one compiler, while C interfaces are far steadier.
  • Give realistic situations where ABI instability hurts (mixing toolchains, plugin architectures, shipping prebuilt libraries).
  • Describe engineering practices that reduce ABI risk in C++ code.

Structure your answer clearly, include concrete numbers or code where they help, and point out common mistakes.

Hints

Hint 1

Start from a rule: an object of type T must sit at an address divisible by alignof(T), and sizeof(T) must be a multiple of alignof(T) so arrays stay aligned. Work out a struct with a char, an int and another char by hand, then reorder it.

Hint 2

For the ABI part, think about everything two separately compiled binaries must agree on without seeing each other's source: how arguments are passed, symbol names, field offsets, vtable slots, and the internals of standard library types that live in headers.

Hint 3

For mitigation, think about shrinking the binary surface: a flat C boundary, opaque handles, a pointer-to-implementation so private members never appear in the public layout, and allocating and freeing memory on the same side of the boundary.