Developer knowledge network · moderated exchange

UnreliableCode 커뮤니티

개발자 연구, 리버스 엔지니어링 및 코딩 커뮤니티

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주 전 · 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주 전 · 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주 전 · 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.