skip to content

Layout and Alignment

sizeof, alignment and padding decide how big a struct is, and trivially copyable or standard-layout types may be copied as bytes. Interviewers ask why sizeof exceeds the field sum.

on this pageshow

explore

questions

5

In C++, why is sizeof of `struct Small { char tag; int value; };` typically 8 rather than 5?

level: juniorimportance: must knowfreq 68%

answer

  1. every type has an alignment
  2. gaps before a stricter member
  3. arrays need the size to repeat
  4. implementation-defined, not fixed

basics

~20 s

Each member must sit at an address that is a multiple of its type's alignment. With a 4-byte-aligned int, the compiler inserts 3 padding bytes after tag, so value starts at offset 4 and sizeof(Small) is 8 on typical platforms.

solid answer

~40 s

Every object type has an **alignment requirement**, queried with `alignof`, and creating an object at an address that does not meet it is undefined behaviour. Members are laid out in declaration order, so after the 1-byte `tag` the compiler inserts **padding** until the next offset is a multiple of `alignof(int)`, which is 4 on mainstream ABIs, putting `value` at offset 4. `sizeof` is also rounded up to a multiple of the struct's own alignment, adding **tail padding** where needed, so that every element of a `Small[N]` array stays aligned. The standard does not fix any of these numbers: alignments and sizes of fundamental types are implementation-defined, so 8 is what Apple clang 21 printed on arm64, not a guarantee. `offsetof(Small, value)` and Clang's `-Wpadded` show where the gaps are.

code

cpp · 19 lines
cpp
#include <cstddef>
#include <cstdio>
struct Small {
  char tag;    // offset 0, then 3 bytes of padding
  int value;   // offset 4: int needs 4-byte alignment here
};
struct Tail {
  int value;   // offset 0
  char tag;    // offset 4, then 3 bytes of tail padding
};
int main() {
  std::printf("alignof(int) = %zu\n", alignof(int));
  std::printf("sizeof(Small) = %zu, offsetof(Small, value) = %zu\n",
              sizeof(Small), offsetof(Small, value));
  std::printf("sizeof(Tail) = %zu\n", sizeof(Tail));
  Tail arr[2];
  std::printf("arr[1] starts %td bytes after arr[0]\n",
              reinterpret_cast<char*>(&arr[1]) - reinterpret_cast<char*>(&arr[0]));
}

go deeper

for a junior

Explain that members are aligned to their type's alignment, so the compiler inserts padding after a char before an int, and that sizeof includes it.

for a middle

Add tail padding and why arrays need sizeof to be a multiple of alignof, and show offsetof and -Wpadded as ways to inspect a layout.

for a senior

Separate what the standard guarantees from what the ABI chooses, and spot layouts that differ between the platforms a codebase ships on.

for a principal

Decide where layout must be pinned with static_assert, such as structs shared across processes, files or languages, and where it may float with the ABI.

## Alignment comes first Every object type in C++ has an **alignment requirement**: the number of bytes between successive addresses at which an object of that type may be placed. It is always a power of two, you query it with `alignof(T)`, and the standard says that creating an object in storage that does not meet its type's alignment is **undefined behaviour**. The values are implementation-defined. On the mainstream 64-bit ABIs, `char` has alignment 1, `int` 4 and `double` 8, and the narrow character types always have the weakest alignment. ## How a struct is laid out For `struct Small { char tag; int value; };` the compiler places members in declaration order, at increasing addresses: 1. `tag` goes at offset 0 and occupies 1 byte. 2. The next free offset is 1, but `value` needs a multiple of 4, so offsets 1 to 3 become **padding**. 3. `value` goes at offset 4 and occupies 4 bytes, ending at offset 8. 4. The struct's own alignment is the largest member alignment, 4, and 8 is already a multiple of 4, so no tail padding is needed. `sizeof(Small)` is 8. The code example prints exactly these numbers on Apple clang 21 for arm64. ## Why sizeof includes tail padding Reverse the members: `struct Tail { int value; char tag; };` holds 5 bytes of data but `sizeof(Tail)` is still 8. The reason is arrays. Elements of `Tail arr[2]` are placed exactly `sizeof(Tail)` bytes apart with no gaps, so if `sizeof` were 5, `arr[1].value` would start at offset 5 and be misaligned. The compiler therefore rounds `sizeof` up to a multiple of `alignof(Tail)`, and the 3 bytes after `tag` are **tail padding**. That rule, `sizeof(T)` being a multiple of `alignof(T)`, is what makes pointer arithmetic over arrays work. ## Tools that show the layout - `sizeof(T)` and `alignof(T)` give the total size and the alignment. - `offsetof(T, member)` from `<cstddef>` gives a member's byte offset; it is guaranteed for **standard-layout** classes and only conditionally supported for others, and Clang warns `'offsetof' on non-standard-layout type` there. - Clang's `-Wpadded` reports every gap, for example `padding struct 'Small' with 3 bytes to align 'value'`. - `static_assert(sizeof(Small) == 8);` turns an assumption into a compile-time check. ## What changes the numbers | Factor | Effect | |---|---| | member order | gaps depend on which member follows which | | target ABI | `long double`, `long` and pointer sizes and alignments differ between platforms | | `alignas` | raises a member's or a type's alignment, never lowers it | | `#pragma pack` and packed attributes | compiler extensions that remove padding at the cost of misaligned members | | virtual functions and virtual bases | add hidden pointers whose placement is the ABI's choice | ## Common wrong answers - "The compiler pads to 8 bytes because the machine word is 8 bytes": `Small` contains no 8-byte member, and its alignment is 4. - "Padding bytes are zero": that is guaranteed only when the object was zero-initialized, as statics are; otherwise their contents are not guaranteed, which matters when you hash, compare or write a struct's raw bytes. - "sizeof is the sum of the member sizes": only when no member needs a gap and the total is already a multiple of the largest alignment. ## Where it bites in practice - **Memory in bulk.** A million `Small` objects cost 8 MB, not 5 MB; padding is paid per element. - **Raw bytes.** Writing a struct with `fwrite` or sending it over a socket also writes its padding, and a reader built by another compiler may expect different offsets. - **Hand-computed offsets.** Code that adds `1` to a `char*` to reach `value` reads padding instead of the member. A good junior answer names alignment, padding and tail padding; a strong one adds that the numbers are the ABI's, not the language's, and shows how to check them with `offsetof` and `static_assert`.

  • What is the size of an empty struct in C++?
    At least 1: a complete object must have a distinct address, so `sizeof(struct Empty {})` is non-zero, typically 1. As a base class, though, an empty class can take no space (the empty base optimization), and since C++20 a member marked `[[no_unique_address]]` may also overlap other members.
  • Are the values of padding bytes defined?
    Not in general. Padding bits are part of the object representation but not of the value representation, so setting the members says nothing about them; only zero-initialization, as for statics or value-initialized aggregates, sets them to zero. Comparing two structs with `memcmp`, hashing their bytes or writing them to a file can therefore differ between objects whose members are equal, unless the padding was cleared first, for example with `memset`.

  • sizeof a struct is always the sum of its members' sizes.
  • Padding is always rounded up to the machine word size, 8 bytes on 64-bit systems.
  • The C++ standard guarantees that int is 4 bytes with 4-byte alignment.
  • Padding bytes are always zero, so comparing structs with memcmp is always safe.
  • Tail padding is wasted space the compiler could drop without consequence.
open as a page

In C++, how does the declaration order of data members change a struct's size, and may the compiler reorder them to save space?

level: middleimportance: should knowfreq 52%

basics

~20 s

Padding depends on which member follows which, so the same members can take 24 or 16 bytes. The compiler may not reorder them; since C++23 every non-static data member is laid out in declaration order, so sorting is your job.

open as a page

In C++, what does `struct alignas(32) Block` guarantee, and why could `new Block` return a misaligned pointer before C++17?

level: seniorimportance: should knowfreq 35%

basics

~20 s

alignas(32) makes alignof(Block) 32 and rounds sizeof up to a multiple of 32, so stack and static objects land on 32-byte boundaries. Before C++17, new ignored such extended alignment; since C++17 it calls operator new(std::size_t, std::align_val_t).

open as a page

A C++ binary file reader memcpys an 18-byte on-disk header into its FileHeader struct and gets a wrong entry_count; why, and how should it read the header?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The struct has padding the file lacks, so entry_count sits at offset 8 in memory but 6 on disk, and a whole-struct memcpy shifts the bytes. Copy each field from its file offset, fix byte order, and assert layout assumptions.

open as a page

In C++, when do you need std::launder or C++23's std::start_lifetime_as instead of a plain reinterpret_cast to use an object in raw storage?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

A reinterpret_cast pointer into storage need not point to the object there. Keep the pointer placement new returns, use std::launder to recompute a pointer to an existing object, and C++23's std::start_lifetime_as to turn existing bytes into an object.

open as a page