Search code examples
gccalignof

Why doesn't gcc honor alignment requirements?


Consider the following C++ code that prints the alignment requirement for a double and the effective alignment of a structure member of type double:

#include <iostream>

struct S { short x; double y; };

int main() {
    S s;
    std::cout << __alignof(double) << ' ';
    std::cout << (char*)&s.y - (char*)&s << std::endl;
}

(Run on codepag.org)

I'm compiling this code with gcc on x86.

I was expecting this program to output 8 8, however it prints 8 4 instead. Why is that?


Solution

  • The alignment of an object can be different outside and inside a structure. Outside the structure it might be the smallest alignment that allows the fastest access (for example 8 byte). But inside the structure it could be the some value which needs the least padding (4 bytes on x86). Some compilers allow you to control the structure packing (gcc:__attribute__((pack)), microsoft: #pragma pack())

    What exactly the compiler does, it determined by the ABI of your system. If the ABI says structure values have no larger padding than four bytes, then the compiler will conform to this.