Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

Knowledge indexيعيش
4Categories
919Threads
2.8Kدعامات
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
مندوب: 163
تاريخ الانضمام: Jan 2019
دعامات: 11
شكرًا: 33
3 weeks ago · 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
مندوب: 146
تاريخ الانضمام: Aug 2019
دعامات: 33
شكرًا: 31
3 weeks ago · 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
مندوب: 186
تاريخ الانضمام: Oct 2021
دعامات: 10
شكرًا: 27
3 weeks ago · 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.