Struct Layout and Binary Compatibility in C++
System DesignModel answerLast 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
alignofrelates 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Overview
Both topics concern the exact bytes a compiler produces. Alignment and padding decide where each member sits inside an object. The ABI is the full agreement that lets separately built binaries interpret those bytes the same way and call one another. Because object layout is part of that agreement, a layout change is an ABI change.
Part 1: Alignment and padding
Alignment. A type T has an alignment requirement alignof(T), and objects of that type must be placed at addresses that are multiples of it. Typical values on x86-64 and AArch64 Linux:
| Type | Alignment |
|---|---|
char | 1 |
short | 2 |
int, float | 4 |
double, long, pointers | 8 |
A struct's alignment is the largest alignment among its members.
Padding. Compilers add unnamed filler bytes in two places:
- Interior padding between members so each lands on its boundary.
- Tail padding after the last member so that
sizeof(S)is a multiple ofalignof(S), which keeps every element ofS arr[N]aligned.
Reordering example:
struct A { char a; int b; char c; }; // a@0, pad 3, b@4, c@8, pad 3 -> 12
struct B { int b; char a; char c; }; // b@0, a@4, c@5, pad 2 -> 8
struct C { char a; double d; char c; }; // 1 + 7 + 8 + 1 + 7 = 24
struct D { double d; char a; char c; }; // 8 + 1 + 1 + 6 = 16
static_assert(sizeof(A) == 12 && alignof(A) == 4);
static_assert(sizeof(B) == 8);
Ordering members from largest to smallest alignment usually minimizes padding. The trade-off is that fields used together may end up apart, which can hurt cache locality, so measure on hot paths. At scale it matters: a million C objects use 8 MB more than a million D objects.
Why alignment exists
- Hardware: some architectures fault on misaligned loads and stores. Others (x86) tolerate them but may split an access across cache lines or pages, costing cycles.
- Atomicity: naturally aligned accesses are atomic on mainstream CPUs; a misaligned access crossing a cache line is not, and atomic instructions may fault.
- SIMD: aligned vector loads and stores need 16-, 32- or 64-byte alignment.
Problems it causes
- Surprising sizes and memory bloat, as above.
- Binary data. Calling
fwriteormemcpyon a struct emits padding bytes with indeterminate values. That can leak stack contents and makes files differ between platforms. Sizes also vary:longis 4 bytes on 64-bit Windows and 8 on 64-bit Linux, and endianness differs between machines. - Undefined behavior. Dereferencing a
reinterpret_cast<int*>(buf + 1)is UB even where the hardware tolerates it. The compiler may assume alignment and emit aligned vector instructions that then crash. - Compatibility. Adding or reordering a member shifts offsets, and previously compiled code silently reads the wrong bytes.
Inspecting and controlling layout
- Inspect with
sizeof,alignof,offsetof,pahole,-Wpadded, or MSVC's/d1reportSingleClassLayout. Lock the expected layout in withstatic_assert. - Raise alignment with
alignas(64), for example to prevent false sharing between threads. This is portable and low risk. - Lower alignment with
#pragma pack(1)or__attribute__((packed)). This is non-portable and risky:- A pointer to a packed member can be misaligned (GCC warns with
-Waddress-of-packed-member). - Accesses may compile to slower byte-wise code, and atomics on such members break.
- A forgotten
#pragma pack(pop)changes the layout of every struct in later headers.
- A pointer to a packed member can be misaligned (GCC warns with
- For file and network formats, prefer explicit serialization: copy each field with
memcpyinto a byte buffer, using fixed-width types and a chosen byte order.
Part 2: ABI and why C++ breaks it
API vs. ABI. An API is a source-level contract (names, signatures, semantics); preserving it lets users recompile. An ABI is the machine-level contract; preserving it lets users relink or swap a shared library without recompiling.
What an ABI covers
- Calling convention: argument registers, stack cleanup, how structs are returned (System V AMD64 vs. Microsoft x64).
- Data layout: sizes, alignment, padding, bit-fields, endianness.
- Name mangling:
foo(int)becomes_Z3fooiunder the Itanium ABI and?foo@@YAXH@Zunder MSVC. - Object model: vtable layout and order, vptr placement, RTTI, thunks for multiple and virtual inheritance, member-pointer representation.
- Exception handling: unwind tables and personality routines.
- Runtime details: allocation and deallocation pairing, static-initialization guards, thread-local storage, and the layout of standard-library types.
Why C is steadier. C has no overloading, classes, templates or exceptions. Its ABI is essentially the platform calling convention plus struct layout, which the OS or platform vendor defines once.
Why C++ is fragile
- No standard ABI. The ISO standard does not define one. GCC and Clang use the Itanium ABI; MSVC has its own, and it changed with nearly every major release until Visual Studio 2015, since when 2015 to 2022 are binary compatible.
- The standard library is part of the ABI. Templates are instantiated in the client's binary, so the private layout of
std::stringorstd::vectoris effectively public. libstdc++ had to introduce a dual ABI (_GLIBCXX_USE_CXX11_ABI) when C++11 banned copy-on-write strings. libstdc++, libc++ and MSVC STL are mutually incompatible. - Build flags change layout. Examples: MSVC's
_ITERATOR_DEBUG_LEVEL, Debug vs. Release runtimes,-fno-rtti,-fno-exceptions, language-standard switches,#pragma pack. - Harmless-looking edits break it. Adding a private member, adding or reordering virtual functions, or changing inline bodies all alter the binary contract while the API appears unchanged.
Practical failures
- A shared library built with one GCC ABI mode used by an application built with the other: link errors on
__cxx11symbols, or silent heap corruption if headers disagree. - A plugin host loading a plugin built with different flags or a different compiler: vtable offsets disagree, and a virtual call lands in the wrong function.
- Windows DLLs with separate CRTs: memory allocated in one module and freed in another crashes because each runtime has its own heap.
- Vendors shipping prebuilt SDKs must provide a binary per compiler, version and configuration.
Mitigation strategies
- Flat C boundary: expose
extern "C"functions, fixed-width integers, plain structs and opaque handles; wrap them in a header-only C++ convenience layer on the client side. - Keep STL types out of the public interface: pass
const char*plus length, or spans of POD data. - PImpl: hide private members behind a pointer so the public class has a stable size and layout; add new data to the implementation freely.
- Own your memory across the boundary: provide
create/destroyfunctions so allocation and release occur in the same module. - Version carefully: add new virtual functions only at the end of an interface, use versioned structs with a size field, and use inline namespaces for versioned symbols.
- Control the toolchain: if a C++ interface is unavoidable, build every component with the same compiler, standard library, runtime and flags, and check in CI with ABI tools such as
abidiff. - Pin layout in tests:
static_assertonsizeof,alignofandoffsetoffor any exported type.
Common mistakes
- Assuming "it compiled and linked" means "it is compatible."
- Treating
#pragma packas a harmless size optimization. - Writing structs directly to disk or the network.
- Exporting
std::stringorstd::vectoracross a DLL boundary. - Adding a virtual function in the middle of a class in a released interface.
A strong answer links the halves: padding and offsets are part of the layout, layout is part of the ABI, so any change to members, order, packing or flags is a potential binary break.