Module 9 · Performance
9.1Layout, alignment and padding
See how a struct is laid out in memory: why every type has an alignment, where the compiler adds padding, how ordering members shrinks a struct, and when to use alignas, packed structs and [[no_unique_address]].
On this page
- Key terms
- In 30 seconds
- Size and alignment
- Padding between members
- Arrays and the stride
- Ordering members to shrink a struct
- Asking for more alignment: alignas
- Packed structs, and why to avoid them
- Members that take no room: [[no_unique_address]]
- Copying as bytes: trivially copyable types
- Which one should I use?
- Under the hood
- Common pitfalls
- Reading a number through a cast pointer
- alignas needs a power of 2
- Try it yourself
Key terms
- alignment (
alignof(T)) - The number every address of a
Tmust be a multiple of.alignof(double)is 8 on this platform, so adoublestarts at a multiple of 8. - padding
- Unused bytes the compiler adds inside a struct, between members or at the end, so every member sits at an address its alignment allows.
- offset
- Where a member starts, counted in bytes from the start of its object.
offsetof(T, member)from<cstddef>gives it. - stride
- The distance in bytes from one element of an array to the next. For an array of
Tit'ssizeof(T), padding included. alignas(N)- Asks for an alignment of at least
Nbytes for a type or a variable.Nmust be a power of 2. - packed struct
- A struct whose padding a compiler extension removes, so its members can sit at misaligned addresses.
[[no_unique_address]]- An attribute that lets a member of an empty type take no bytes in its struct.
- trivially copyable
- A type whose objects can be copied byte by byte, like a struct of numbers.
std::is_trivially_copyable_v<T>checks it.
A struct’s size isn’t always the sum of its members. The compiler puts each member at an address the processor can read it from easily, and leaves gaps where it has to. When you store millions of objects, those gaps cost memory and, as the next lesson shows, speed. This lesson shows where they come from and how to get rid of them.
In 30 seconds
- Every type has an alignment: its objects start at addresses that are a multiple of
alignof(T). - The compiler adds padding between members and at the end of a struct so that every member is aligned, in an array too.
- Ordering members from the largest alignment to the smallest usually removes most of the padding.
alignasasks for more alignment. Packed structs remove padding but leave members misaligned: avoid them.
Size and alignment
You know sizeof from Variables. Its partner alignof gives a type’s alignment: the number every address of that type must be a multiple of.
#include <print>
#include <string>
std::println("char {} {}", sizeof(char), alignof(char));
std::println("short {} {}", sizeof(short), alignof(short));
std::println("int {} {}", sizeof(int), alignof(int));
std::println("double {} {}", sizeof(double), alignof(double));
std::println("int* {} {}", sizeof(int*), alignof(int*));
std::println("string {} {}", sizeof(std::string), alignof(std::string));Output
char 1 1 short 2 2 int 4 4 double 8 8 int* 8 8 string 32 8
For these built-in types, the alignment equals the size on this platform: an int starts at a multiple of 4, a double at a multiple of 8. A std::string is 32 bytes but only needs 8, the alignment of the pointer inside it. The standard guarantees only that an alignment is a power of 2 and that alignof(char) is 1; the rest is up to the platform.
Padding between members
A struct’s members are stored in the order you declare them, and each must start at a multiple of its own alignment. When the previous member ends at the wrong place, the compiler skips bytes. Here’s a mutation record, a change from one base to another at a position in a genome:
#include <cstddef>
#include <print>
struct Mutation {
char from;
double score;
char to;
int position;
bool confirmed;
};
int main() {
std::println("size {}, alignment {}", sizeof(Mutation), alignof(Mutation));
std::println("from {}, score {}, to {}", offsetof(Mutation, from),
offsetof(Mutation, score), offsetof(Mutation, to));
std::println("position {}, confirmed {}", offsetof(Mutation, position),
offsetof(Mutation, confirmed));
}Output
size 32, alignment 8 from 0, score 8, to 16 position 20, confirmed 24
The members add up to 1 + 8 + 1 + 4 + 1 = 15 bytes, but a Mutation is 32. offsetof(T, member), from <cstddef>, gives each member’s offset, the byte where it starts, and shows the gaps:
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Mutation | from1 byte | padding7 bytes | score8 bytes | to1 byte | padding3 bytes | position4 bytes | confirmed1 byte | padding7 bytes | 32 bytes | ||||||||||||||||||||||||
A Mutation is 32 bytes on this platform. from takes byte 0, then 7 bytes of padding so that score starts at byte 8. score takes bytes 8 to 15, to takes byte 16, 3 bytes of padding follow so that position starts at byte 20. position takes bytes 20 to 23, confirmed takes byte 24, and 7 bytes of padding at the end make the size 32, a multiple of 8.
GCC and Clang on 64-bit Linux follow three rules:
- Each member starts at an offset that’s a multiple of its alignment:
scorecan’t start at byte 1, so it starts at 8. - The struct’s alignment is the largest alignment of its members: 8, from
score. - The size is rounded up to a multiple of the struct’s alignment: 25 bytes of members and gaps become 32.
offsetof is only guaranteed to work on simple structs like this one: no virtual functions, and every data member public.
Arrays and the stride
Rule 3 exists because of arrays. The elements of an array sit side by side, so the distance from one to the next, the stride, is sizeof(T). If a Mutation were 25 bytes, the second element’s score would start at byte 25 + 8 = 33, not a multiple of 8. The padding at the end keeps every element aligned:
#include <cstdint>
#include <print>
struct Mutation {
char from;
double score;
char to;
int position;
bool confirmed;
};
int main() {
Mutation batch[3] = {};
auto first = reinterpret_cast<std::uintptr_t>(&batch[0]);
auto second = reinterpret_cast<std::uintptr_t>(&batch[1]);
auto score = reinterpret_cast<std::uintptr_t>(&batch[1].score);
std::println("stride {}, whole array {}", second - first, sizeof(batch));
std::println("second score at a multiple of 8: {}", score % 8 == 0);
}Output
stride 32, whole array 96 second score at a multiple of 8: true
reinterpret_cast<std::uintptr_t>(p) turns a pointer into its address as a whole number, so you can do arithmetic on it. std::uintptr_t, from <cstdint>, is an unsigned integer type big enough to hold any address. A std::vector<Mutation> has the same stride: 32 bytes per element, 17 of them padding.
Ordering members to shrink a struct
The compiler never reorders members for you, so the order is your choice. Put the members with the largest alignment first and the small ones together at the end, and the gaps mostly disappear:
#include <print>
struct CompactMutation {
double score;
int position;
char from;
char to;
bool confirmed;
};
int main() {
std::println("{}", sizeof(CompactMutation));
}Output
16
Same members as Mutation, half the size. A million mutations now take 16 MB instead of 32 MB, and twice as many fit in each block of memory the processor loads:
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Mutation | from1 byte | padding7 bytes | score8 bytes | to1 byte | padding3 bytes | position4 bytes | confirmed1 byte | padding7 bytes | 32 bytes | ||||||||||||||||||||||||
CompactMutation | score8 bytes | position4 bytes | from1 byte | to1 byte | confirmed1 byte | padding1 byte | 16 bytes | ||||||||||||||||||||||||||
Mutation, in declaration order, is 32 bytes with 17 bytes of padding in three places. CompactMutation puts score first (bytes 0 to 7), then position (bytes 8 to 11), then from, to and confirmed at bytes 12, 13 and 14, with 1 byte of padding at the end: 16 bytes.
To find the gaps without counting, ask the compiler. -Wpadded warns about every byte of padding it adds. It’s too noisy to leave on, since almost every struct has some, but it’s handy for checking one struct. With warnings as errors, it stops the build at the first gap:
struct Mutation {
char from;
double score;
char to;
int position;
bool confirmed;
};
int main() {
Mutation m{};
}The compiler rejects this
main.cpp:3:12: error: padding struct to align ‘Mutation::score’ [-Werror=padded]
3 | double score;
| ^~~~~
compilation terminated due to -fmax-errors=1.CompactMutation would still get one warning, for the byte at the end: you can’t avoid that one, because 15 bytes must round up to a multiple of 8.
PerformanceSmaller structs, fewer trips to memory
When a loop goes through a big array of structs, its speed often depends on how many bytes it reads. Halving the size of each element can make such a loop much faster. Caches and data-oriented design measures this.
Asking for more alignment: alignas
alignas(N) raises the alignment of a type or a variable to N. Two uses come up in this course: SIMD instructions read 32 bytes at a time and are fastest from an address that’s a multiple of 32 (SIMD), and data that different threads write should sit in separate 64-byte blocks (Mutexes and atomics).
#include <cstdint>
#include <print>
#include <vector>
struct alignas(64) Counter {
long hits;
};
int main() {
std::println("{} {}", sizeof(Counter), alignof(Counter));
alignas(32) float weights[8] = {};
std::vector<Counter> counters(4);
auto w = reinterpret_cast<std::uintptr_t>(weights);
auto c = reinterpret_cast<std::uintptr_t>(counters.data());
std::println("{} {}", w % 32, c % 64);
}Output
64 64 0 0
A Counter holds one 8-byte long, but it’s 64 bytes: rule 3 rounds its size up to its alignment. alignas on a variable, like weights, changes where that variable goes and nothing else. Since C++17, new and std::vector respect alignments bigger than usual, so every element of counters starts at a multiple of 64.
Packed structs, and why to avoid them
GCC and Clang can remove padding altogether. [[gnu::packed]] is a compiler extension, not standard C++, that puts each member right after the previous one. The RecordHeader below is 5 bytes, not 8.
That looks like a neat way to match a binary file format byte for byte, but length now starts at byte 1, an address that isn’t a multiple of 4: it’s misaligned. Reading header.length directly works, because the compiler knows the member is packed and reads it carefully. A pointer to it loses that knowledge, so both compilers refuse to make one:
#include <cstdint>
#include <print>
struct [[gnu::packed]] RecordHeader {
char tag;
std::uint32_t length;
};
int main() {
RecordHeader header{'R', 42};
std::uint32_t* length = &header.length;
std::println("{}", *length);
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:12:29: error: taking address of packed member of ‘RecordHeader’ may result in an unaligned pointer value [-Werror=address-of-packed-member]
12 | std::uint32_t* length = &header.length;
| ^~~~~~~~~~~~~~
cc1plus: all warnings being treated as errorsThe fix is to copy the value out first: std::uint32_t length = header.length;. #pragma pack(1) before a struct does the same as [[gnu::packed]] and also works with Microsoft’s compiler. Both make every access to a misaligned member slower, are easy to misuse through pointers and references, and give layouts that can differ between compilers. To read a binary format, read its bytes and copy each field out with std::memcpy, as the pitfall below shows.
Members that take no room: [[no_unique_address]]
Every object needs its own address, so even a struct with no members is 1 byte. As a member, it also brings padding. Empty types turn up as options: a logger that does nothing in a release build, or a rule for comparing values. [[no_unique_address]] lets such a member share its address with the others and take no room:
#include <print>
struct NoLog {};
struct Counter {
NoLog log;
int value;
};
struct SlimCounter {
[[no_unique_address]] NoLog log;
int value;
};
int main() {
std::println("{} {} {}", sizeof(NoLog), sizeof(Counter),
sizeof(SlimCounter));
}Output
1 8 4
The standard library uses the same idea inside its containers. Microsoft’s compiler ignores the standard attribute and needs [[msvc::no_unique_address]] instead.
Copying as bytes: trivially copyable types
A struct of numbers is fully described by its bytes, so copying the bytes copies the object. Such a type is trivially copyable, and std::is_trivially_copyable_v<T>, from <type_traits>, checks it. A struct that holds a std::string isn’t: the string owns a heap block, and a byte copy would make two strings own the same block.
#include <print>
#include <string>
#include <type_traits>
struct Score {
int position;
float value;
};
struct Read {
std::string id;
std::string bases;
};
int main() {
std::println("{}", std::is_trivially_copyable_v<Score>);
std::println("{}", std::is_trivially_copyable_v<Read>);
}Output
true false
Only trivially copyable types can be copied with std::memcpy, written to a file as raw bytes, or reinterpreted with std::bit_cast (Bits, bit_cast and endianness). Their padding bytes are copied too, and those hold whatever was in memory before, so never compare two structs byte by byte.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
| The order that reads best | Most structs, and anything you only have a few of. | Clear code is worth more than a few bytes. | Group members by meaning. |
| Largest alignment first | Structs you store by the thousand or million: reads, k-mers, mutations, pixels. | Removes most padding, so arrays are smaller and faster to scan. | Pointers and doubles, then ints and floats, then chars and bools. |
alignas(N) | Data for SIMD loads, or data that different threads write. | Puts it on a 32- or 64-byte boundary. | struct alignas(64) Counter { … }; |
[[no_unique_address]] | A member whose type is empty. | The member stops costing bytes. | [[no_unique_address]] NoLog log; |
| A packed struct | Almost never. | Misaligned members: slower, easy to misuse, not portable. | Copy fields out of the bytes with std::memcpy instead. |
Rule of thumb: for structs you keep many of, order members from the largest alignment to the smallest and check sizeof with a static_assert. Leave the rest in the order that reads best.
Under the hood
The processor reads memory in aligned chunks: 8 bytes at a time into a register, 64 bytes at a time from main memory. An aligned value never straddles two chunks, so one read gets all of it. x86-64 processors can still read a misaligned value, but more slowly when it crosses a 64-byte boundary, and some instructions, such as aligned SIMD loads, stop the program instead. Many other processors can’t read misaligned values at all. Because the C++ rules promise that every object is aligned, the compiler is free to pick instructions that rely on it. That’s why a misaligned access is undefined behavior even on x86-64.
Memory from new and std::malloc is aligned enough for any ordinary type. std::max_align_t, from <cstddef>, is a type with that largest ordinary alignment:
#include <cstddef>
#include <print>
std::println("{}", alignof(std::max_align_t));Output
16
The C++ standard fixes little of what this lesson printed: members come in declaration order, and there may be padding. The exact numbers come from the platform’s ABI (application binary interface), the rules every compiler on a platform follows so that code built by one can call code built by another. GCC and Clang on 64-bit Linux share the System V x86-64 ABI. Windows has its own, in which long is 4 bytes, so a struct with a long has a different layout there.
Common pitfalls
Reading a number through a cast pointer
Binary file formats store numbers at any byte offset. Pointing an int* at byte 1 of a buffer compiles, but the int it reads is misaligned, and the sanitizer stops the program:
#include <print>
alignas(4) unsigned char bytes[8] = {7, 42, 0, 0, 0, 0, 0, 0};
const int* value = reinterpret_cast<const int*>(bytes + 1);
int number = *value;
std::println("{}", number);This fails when it runs
main.cpp:5:14: runtime error: load of misaligned address 0x… for type 'const int', which requires 4 byte alignment
0x…: note: pointer points here
00 00 00 07 2a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 c0 ae 48 c0
^Copy the bytes into a real int instead. std::memcpy(destination, source, count), from <cstring>, copies count bytes and doesn’t care about alignment; compilers turn a small one like this into a single load:
#include <cstring>
#include <print>
unsigned char bytes[8] = {7, 42, 0, 0, 0, 0, 0, 0};
int value = 0;
std::memcpy(&value, bytes + 1, sizeof value);
std::println("{}", value);Output
42
The value is 42 because x86-64 stores the lowest byte of a number first. Bits, bit_cast and endianness covers byte order, and the other reason the cast was wrong: reading an object through a pointer to an unrelated type is undefined behavior even when it’s aligned.
alignas needs a power of 2
A 24-byte block can’t be aligned to 24, because alignments are always powers of 2:
struct alignas(24) Block {
float values[6];
};
int main() {
Block b{};
}The compiler rejects this
main.cpp:1:20: error: requested alignment ‘24’ is not a positive power of 2
1 | struct alignas(24) Block {
| ^~~~~Use alignas(32) (the size grows to 32), or leave the alignment alone.
Common pitfallsizeof isn't the sum of the members
Code that adds up member sizes by hand, to write a struct to a file or to step through a buffer, goes wrong as soon as there’s padding. Use sizeof(T) for the stride, and write and read binary files one field at a time.
Try it yourself
Try it yourself
A k-mer search keeps millions of Hit records. Reorder the members of Hit, without changing their types or names, to make it as small as possible.
#include <cstdint>
#include <print>
struct Hit {
std::uint16_t count;
std::uint64_t kmer;
bool reverse;
std::uint64_t read_id;
std::uint32_t position;
};
int main() {
std::println("{} bytes", sizeof(Hit));
std::println("{} MB for 10 million", sizeof(Hit) * 10'000'000 / 1'000'000);
}Expected output
24 bytes 240 MB for 10 million
Show a hint
Sort the members by alignment: the two 8-byte std::uint64_t members first, then the 4-byte position, then the 2-byte count, then the 1-byte bool. The members add up to 23 bytes, which rounds up to 24.
Show a solution
#include <cstdint>
#include <print>
struct Hit {
std::uint64_t kmer;
std::uint64_t read_id;
std::uint32_t position;
std::uint16_t count;
bool reverse;
};
int main() {
std::println("{} bytes", sizeof(Hit));
std::println("{} MB for 10 million", sizeof(Hit) * 10'000'000 / 1'000'000);
}In the original order, count (2 bytes) is followed by 6 bytes of padding before kmer, reverse by 7 bytes before read_id, and position by 4 bytes at the end: 17 bytes of padding. Largest-first leaves only 1 byte at the end, so a Hit drops from 40 to 24 bytes and ten million of them from 400 MB to 240 MB.
Saved in this browser only.