Developer knowledge network ยท moderated exchange

Komunitas Kode Tidak Dapat Diandalkan

Riset Pengembang, Rekayasa Terbalik & Komunitas Pengkodean

Knowledge indexHidup
4Categories
919Threads
2.8KPostingan
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
Reputasi: 163
Tanggal Bergabung: Jan 2019
Postingan: 11
Terima kasih: 33
3 minggu yang lalu ยท 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
Reputasi: 146
Tanggal Bergabung: Aug 2019
Postingan: 33
Terima kasih: 31
3 minggu yang lalu ยท 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
Reputasi: 186
Tanggal Bergabung: Oct 2021
Postingan: 10
Terima kasih: 27
3 minggu yang lalu ยท 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.