Search code examples
c++visual-c++alignmentmemory-alignment

How do compilers implement __declspec(align(x)) / __attribute__((aligned(x)))?


Imagine a structure like this:

struct S {
    __declspec(align(32)) double A[4]; // MSVC / ICL on Windows
    double A[4] __attribute__((aligned(x))); // CLANG / GCC
};

The structure can be allocated on stack or using malloc for instance, either way the structure instance itself may not be aligned. So can we count on the member A being 32-byte aligned? If so how does the compiler do that?


Solution

  • At least for MSVC as the docs for __declspec(align()) say it only affects static and automatic object allocations, not dynamic allocations. If you want to control dynamic allocation alignment you will need to use a function such as _aligned_malloc that provides that ability.