Search code examples
c++sizeof

Size of structure - padding and alignment


I have an explicitly sized structure as follow:

typedef struct
{
    unsigned long                   A : 4;
    unsigned long                   B : 12;
    union
    {
        unsigned long               C1 : 8;
        unsigned long               C2 : 8;
        unsigned long               C3 : 8;
    };
    unsigned long                   D : 8;
}FooStruct;

The total size of this struct should be 32bit (4 bytes) in theory. However, I get a 12-byte size using sizeof so there should be some padding and alignment happening here.

I just don't see why and where. Can someone explain to me how this structure takes 12 bytes in memory?


Solution

  • The union forces the start of a new unsigned long, and the member after the union yet another unsigned long. Assuming long is 4 bytes that means your struct will have 3 unsigned longs for a total of 12 bytes. Although a union with three equally sized members also seems odd.

    If you want this to have a size of 4 bytes why not change it to:

    typedef struct
    {
        unsigned short                   A : 4;
        unsigned short                   B : 12;
    
        union
        {
            unsigned char               C1 : 8;
            unsigned char               C2 : 8;
            unsigned char               C3 : 8;
        };
    
        unsigned char                   D : 8;
    }FooStruct;