Home > Software engineering >  Why structure and its typedef consume different size when aligned?
Why structure and its typedef consume different size when aligned?

Time:05-11

I was expecting both sizes are 8 but i get sizeof(myStruct) = 16, sizeof(myType) = 8. I compiled this on Windows 64-bit machine with MinGW.

#include <stdio.h>
#include <stdint.h>

struct s1{
    int8_t a;
    int32_t b; 
} __attribute__((aligned));

typedef struct{
    int8_t a;
    int32_t b;
}s2 __attribute__((aligned));

struct s1 myStruct;
s2 myType;

int main(int argc, char **argv)
{
    printf("sizeof(myStruct) = %zu, sizeof(myType) = %zu\n", sizeof(myStruct), sizeof(myType));
    return 0;
}

CodePudding user response:

struct s1 { … } __attribute__((aligned)); says the members of struct s1 should be aligned to the “maximum alignment” for the target, which is apparently 8 bytes. So each member is put at a multiple of 8 bytes, making the whole structure 16 bytes. (The GCC documentation on this fails to state that specifying this attribute for the structure affects its members, but that appears to be the case.)

typedef struct { … } s2 __attribute__((aligned)); says s2 is a structure with ordinary alignment requirements, so its b member is put at a multiple of 4 bytes and the total size is 8 bytes, and then the s2 type should be aligned to the “maximum alignment”. Thus, when s2 objects are created, they will be put at locations that are multiples of 8, but the layout of members within them will not change.

To make the structure defined with the typedef have the same layout as struct s1, you can use typedef struct { … } __attribute__((aligned)) s2;.

  • Related