Alignment of a struct with two doubles is 4 even though double is aligned to 8 (32bit)

Viewed 561

I'm on a x86_64 machine, with Ubuntu 16.04 and gcc 5.4.0.

I've encountered this somewhat strange behavior today.

$ cat main.c
#include <stdio.h>
struct dd { double d1; double d2; };
int main()
{
    printf("%d\n", (int)__alignof__(double));
    printf("%d\n", (int)__alignof__(struct dd));
}
$ gcc -m32 -o main main.c && ./main
8
4

__alignof__ returns 8 for double and 4 for struct dd. I think it is strange for a struct to be aligned in smaller unit than its members. This behavior is even contrary to the ISO C standard mentioned in the gcc 5.4.0 doc:

Note that the alignment of any given struct or union type is required by the ISO C standard to be at least a perfect multiple of the lowest common multiple of the alignments of all of the members of the struct or union in question.

What may be the reason for this behavior? Is aligning this struct to 4 byte an optimized way to access memory?

1 Answers
Related