Search code examples
cgccstructuresizeofbit-fields

Structure size issue, claiming unrquired memory?


#include <stdio.h>

int main()
{
    struct {
        int a : 1; // bit field sized 1
        double b;
    }structVar;
    //structVar.a = 10;
    printf("%d",sizeof(structVar));
}

size of structVar is 16 at gcc compiler on linux machine. According to me it should be 9. 8 for double and 1 for int bit field.

Any idea Why ?


Solution

  • Structure is aligned (and padded) to size of its largest member - in that case, to sizeof(double). This is expected (although not required by standard) and predictable. It doesn't matter if second member would be int, short or whatever, - as long as it is smaller than double, sizeof struct will be 16.

    Structure packing may reduce size of structure. E.g. gcc allows to #pragma pack(n) to set new alignment for subsequent structures, so with alignment 4 it will be 12 bytes.

    Reason is, if you'll have array of this structures, second structure will be unaligned. It may have performance hits or even failures on some CPUs.