Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
Discussion

Solving memory alignment issues and struct padding with alignas and alignof in C11/C++11 [StackOverflow Architecture Guide]

memory_model_mook
Low-Level C Veteran
MEMBER
Vertreter: 163
Beitrittsdatum: Jan 2019
Beiträge: 11
Danke: 33
Vor 3 Wochen · Jul 29, 2026 11:08 PM
#1

Why sizeof(MyStruct) is often larger than the sum of its member variables:

CPP
struct UnalignedData {
    char a;     // 1 byte
    // 7 bytes of padding inserted by compiler!
    double b;   // 8 bytes (must align to 8-byte boundary)
    int c;      // 4 bytes
    // 4 bytes of tail padding!
}; // Total: 24 bytes

By reordering members from largest to smallest (double b; int c; char a;), the total struct size drops to 16 bytes without changing functionality, saving 33% memory and improving CPU cache line efficiency.

profiler_pat
Performance Hunter
MEMBER
Vertreter: 146
Beitrittsdatum: Aug 2019
Beiträge: 33
Danke: 31
Vor 3 Wochen · Jul 30, 2026 1:33 AM
#2

Reordering struct fields by descending alignment is one of the easiest zero-cost memory optimizations you can do in C/C++.

assembly_micro_dev
x86_64 Micro-arch
MEMBER
Vertreter: 186
Beitrittsdatum: Oct 2021
Beiträge: 10
Danke: 27
Vor 3 Wochen · Jul 30, 2026 8:17 PM
#3

Also useful when interfacing with AVX SIMD: using alignas(32) ensures 256-bit vectors can use aligned load instructions _mm256_load_ps instead of slower unaligned loads.