Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
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
Rep: 163
Datum pridruživanja: Jan 2019
Postovi: 11
Hvala: 33
3 prije tjedana · 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
Rep: 146
Datum pridruživanja: Aug 2019
Postovi: 33
Hvala: 31
3 prije tjedana · 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
Rep: 186
Datum pridruživanja: Oct 2021
Postovi: 10
Hvala: 27
3 prije tjedana · 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.