Notes
All notes

Structs, Unions, and Memory Layout (C++ Core #8)

sizeof(struct) is not the sum of its members. The compiler inserts anonymous padding so every member sits at an address its alignment allows, and it rounds the total up so arrays of the struct stay aligned. Once you know the two rules, size questions become arithmetic.

struct and class

struct and class are the same thing with different defaults:

struct class
Default member access public private
Default inheritance public private
Layout identical identical
struct S { int x; };            // x is public
class  C { int x; };            // x is private

struct D : S { };               // public inheritance
class  E : S { };               // private inheritance

Use struct for plain data and class for invariants. The compiler emits the same layout for both.

QQuestionDoes changing struct to class change sizeof?
ASolution

No. Access specifiers affect compilation, not layout. The size depends on the members, their order, and their alignment.

Padding and alignment rules

Two rules generate every answer:

  1. Each member is placed at the next offset that is a multiple of its alignment. The gap is padding.
  2. The struct’s alignment is the largest alignment of its members, and its size is rounded up to a multiple of that alignment. The trailing gap is tail padding.
struct A {
    char   a;   // offset 0
    double b;   // offset 8 (7 bytes padding)
    char   c;   // offset 16
};              // size 24 (7 bytes tail padding)
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.42cm, minimum height=0.5cm, font=\tiny}]
  \foreach \i in {0,...,23} \node[c, fill=gray!5] at (\i*0.42,0) {};
  \foreach \i in {0} \fill[orange!45] (\i*0.42-0.21,0.25) rectangle (\i*0.42+0.21,-0.25);
  \foreach \i in {1,...,7} \fill[red!12] (\i*0.42-0.21,0.25) rectangle (\i*0.42+0.21,-0.25);
  \foreach \i in {8,...,15} \fill[blue!25] (\i*0.42-0.21,0.25) rectangle (\i*0.42+0.21,-0.25);
  \foreach \i in {16} \fill[green!30] (\i*0.42-0.21,0.25) rectangle (\i*0.42+0.21,-0.25);
  \foreach \i in {17,...,23} \fill[red!12] (\i*0.42-0.21,0.25) rectangle (\i*0.42+0.21,-0.25);
  \node[font=\scriptsize, anchor=north] at (0.0,-0.35) {a};
  \node[font=\scriptsize, anchor=north] at (4.83,-0.35) {b: 8 bytes};
  \node[font=\scriptsize, anchor=north] at (6.72,-0.35) {c};
  \node[font=\scriptsize, anchor=north, text=red!60!black] at (1.47,-0.95) {padding};
  \node[font=\scriptsize, anchor=north, text=red!60!black] at (8.19,-0.95) {tail padding};
  \node[font=\scriptsize, anchor=north] at (4.83,-1.45) {24 bytes total};
\end{tikzpicture}

On x86-64 with the usual sizes (char 1, short 2, int 4, double 8, pointer 8), sizeof(A) is 24. Reordering the members removes most of the padding:

struct B {
    double b;   // 0
    char   a;   // 8
    char   c;   // 9
};              // 16

Same members, 16 bytes instead of 24. That is why “order members from largest alignment to smallest” is a real optimization.

QQuestionWhy is the size of a struct rounded up to a multiple of its

alignment?

ASolution

So that an array of the struct keeps every element aligned. If A were 17 bytes, arr[1].b would start at offset 25, which is not a multiple of 8.

Worked size calculations

struct C { char a; short b; int c; };      // 8
// a:0, pad 1, b:2..3, c:4..7

struct D { char a; int b; char c; };       // 12
// a:0, pad 1..3, b:4..7, c:8, tail pad 9..11

struct E { char a; char b; short c; int d; };  // 8
// a:0, b:1, c:2..3, d:4..7

offsetof gives the offsets at compile time (for standard-layout types):

#include <cstddef>
static_assert(offsetof(A, b) == 8);
static_assert(sizeof(A) == 24);
static_assert(alignof(A) == 8);

A nested struct takes its own alignment into account:

struct Inner { int x, y; };           // size 8, align 4
struct Outer { char c; Inner in; };   // c:0, pad 1..3, in:4..11, size 12

struct Big { char c; double d; };     // size 16, align 8
struct Wrap { char c; Big b; };       // c:0, pad 1..7, b:8..23, size 24

An empty struct has size 1, not 0, because every object needs a distinct address:

struct Empty {};
sizeof(Empty);        // 1

When empty structs are members or base classes, the compiler may optimise them away (empty base optimization), but two empty members of the same type still need distinct addresses, so a naive { Empty a, b; } is 2 bytes.

QQuestionstruct S { char c; int i; }; — what are sizeof(S) and

offsetof(S, i)?

ASolution

8 and 4. Three padding bytes after c, then i at offset 4, total 8.

sizeof and alignof

sizeof reports bytes, alignof reports the required alignment. Both are compile-time constants for complete types.

sizeof(char)        // 1, by definition
sizeof(int)         // 4 on most platforms, not guaranteed by the standard
sizeof(long)        // 8 on LP64 (Linux/macOS), 4 on Windows LLP64
sizeof(void*)       // 8 on 64-bit
sizeof(A)           // includes padding
alignof(A)          // 8
sizeof(A[3])        // 3 * 24 = 72

sizeof on an array is the whole array; on a pointer it is the pointer. That is the same decay rule as Ch. 2.

sizeof of a reference gives the size of the referred type, not the reference:

int x;
int& r = x;
sizeof(r) == sizeof(int);    // true

sizeof is an operator, not a function, and it does not evaluate its operand. In C, variable-length arrays make sizeof a runtime operation; C++ has no VLAs in the standard.

QQuestionWhy is sizeof(long) a bad thing to assume in a program that must

run on Windows and Linux?

ASolution

Windows uses LLP64 (long is 4 bytes), Linux uses LP64 (long is 8). Use int64_t/int32_t when the width matters.

union

A union holds one member at a time, all starting at offset 0. Its size is the largest member rounded up to the largest alignment.

union U {
    char   c;    // 1
    int    i;    // 4
    double d;    // 8
};
sizeof(U);       // 8
alignof(U);      // 8

All members overlap. Writing one and reading another is called type punning:

U u;
u.i = 0x41424344;
std::cout << u.c;    // reads the first byte of i: implementation-defined/UB

In C++, reading a member other than the one last written is undefined behaviour (with a narrow exception for the common initial sequence of standard-layout structs in a union). The portable way to inspect bytes is memcpy:

int i = 0x41424344;
unsigned char bytes[4];
std::memcpy(bytes, &i, 4);

A union is still useful for storage: a variant-like type that stores one of several alternatives, with an explicit tag telling you which one is active. That is what std::variant does, with the tag handled for you (Ch. 10).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.5cm, minimum height=0.45cm, font=\tiny}]
  \foreach \i in {0,...,7} \node[c, fill=gray!5] at (\i*0.5,0) {};
  \node[c, fill=red!25] at (0,0) {};
  \node[font=\scriptsize, anchor=east] at (-0.3,0) {c};
  \foreach \i in {0,...,7} \node[c, fill=gray!5] at (\i*0.5,-0.7) {};
  \foreach \i in {0,...,3} \fill[orange!35] (\i*0.5-0.25,-0.475) rectangle (\i*0.5+0.25,-0.925);
  \node[font=\scriptsize, anchor=east] at (-0.3,-0.7) {i};
  \foreach \i in {0,...,7} \node[c, fill=gray!5] at (\i*0.5,-1.4) {};
  \foreach \i in {0,...,7} \fill[blue!20] (\i*0.5-0.25,-1.175) rectangle (\i*0.5+0.25,-1.625);
  \node[font=\scriptsize, anchor=east] at (-0.3,-1.4) {d};
  \node[font=\scriptsize, anchor=north] at (1.75,-1.75) {all members begin at offset 0; size is the largest};
\end{tikzpicture}
QQuestionCan a union have a constructor and destructor?
ASolution

Yes, but you must manage the active member yourself. A union with a non-trivial member needs user-provided special members, because the compiler cannot know which member to destroy.

Endianness

Endianness is the byte order of a multi-byte value in memory.

uint32_t x = 0x01020304;
unsigned char b[4];
std::memcpy(b, &x, 4);

// little-endian: b = {0x04, 0x03, 0x02, 0x01}
// big-endian:    b = {0x01, 0x02, 0x03, 0x04}

Detecting it at runtime:

bool littleEndian() {
    uint16_t x = 1;
    unsigned char c;
    std::memcpy(&c, &x, 1);
    return c == 1;
}

Serialization must pick an order. htonl/ntohl convert between host and network (big-endian) order. Writing a raw struct to a file and reading it on another machine is a bug for this reason: padding and byte order are both platform-specific.

Bit-fields (unsigned flags : 3;) have implementation-defined layout: which bit comes first, how padding works, and whether they can cross a storage unit. Do not use them for wire formats.

QQuestionWhy is memcpy safer than a union or a cast for inspecting bytes?
ASolution

memcpy has defined semantics for copying object representations and is optimized to a load. Reading a different union member or dereferencing a reinterpret-cast pointer violates the aliasing rules.

Memory layout of arrays and objects

An array is contiguous, so element i is at base + i * sizeof(T). That is why std::vector guarantees contiguity and why pointer arithmetic works on it.

A polymorphic object usually begins with a hidden vptr:

struct Base { virtual void f(); int x; };
// typical layout: [vptr 8 bytes][x 4 bytes][padding 4 bytes] -> size 16

Multiple inheritance can add more vptrs (one per polymorphic base), and a derived class may have base subobjects at nonzero offsets. Do not hard-code these offsets.

Member functions do not take space in the object; virtual functions do, through the vptr and the per-class vtable. Static members do not take space in the object either; they live in static storage.

struct S {
    int x;                 // 4 bytes per object
    static int count;      // 0 bytes per object, one global
    void f();              // 0 bytes per object
};
QQuestionWhy is sizeof(std::string) around 32 bytes while the text may be

2 bytes?

ASolution

The string object stores a pointer, size, capacity, and possibly a small buffer. The characters live on the heap (or in the small-buffer area) and are not part of sizeof.

Global variables and initialization

Objects with static storage duration are zero-initialized before any other initialization, then constant-initialized, then dynamically initialized.

int a;                       // zero-initialized to 0
int b = 42;                  // constant initialization
int c = compute();           // dynamic initialization, before main

Dynamic initialization order across translation units is unspecified. This is the static initialization order fiasco:

// a.cpp
int x = 1;
// b.cpp
extern int x;
int y = x + 1;      // may run before x is initialized

The standard fix is a function-local static, which is initialized on first use:

int& getX() {
    static int x = 1;    // initialized once, thread-safe since C++11
    return x;
}

C++20’s constinit requires constant initialization and turns the fiasco into a compile error:

constinit int x = 1;      // must be constant-initialized
QQuestionWhy is static int x = f(); inside a function safer than a global

int x = f();?

ASolution

The function-local static is initialized on first call, after all dynamic initialization is done and in a defined order relative to its use. Globals across TUs have unspecified order.

Deep: calculate the size

Use this checklist:

  1. List each member with its size and alignment.
  2. Place each at the next multiple of its alignment; record padding.
  3. Struct alignment = maximum member alignment.
  4. Round the final offset up to the struct alignment.
  5. For arrays, multiply by the rounded size.

Five exercises, x86-64 rules (char 1, short 2, int/float 4, double/pointer 8):

Struct Layout Size
{char a; char b; int c;} 0, 1, 4 8
{char a; double b; char c;} 0, 8, 16 → round 24 24
{int a; char b; short c;} 0, 4, 6 → round 8 8
{double a; int b; char c;} 0, 8, 12 → round 16 16
{char a[3]; int b;} 0..2, pad, 4 8

With a union inside:

union U { char c; int i; };         // size 4, align 4
struct S { char a; U u; };          // a:0, pad 1..3, u:4..7, size 8

With #pragma pack(1) or __attribute__((packed)), padding is removed and the size becomes the sum. The cost is unaligned accesses: slower on x86, a fault on some architectures, and technically UB for references to misaligned members.

QQuestionstruct S { char c; double d; }; — how large is S, and how large

is S[10]?

ASolution

16 and 160. d must be at offset 8, so 7 bytes of padding; the total is a multiple of 8, so there is no extra tail padding.

Bugs and edge cases

QQuestionWhy can two runs of the same program produce different bytes when

writing a struct with fwrite?

ASolution

Padding bytes are not initialized by the member assignments, so they contain whatever was on the stack. The object representation includes those bytes.

Next: Exceptions and Resource Management (C++ Core #9) — unwinding, guarantees, and destructors that must not throw.