c++cstructurepadding

structure padding on 64bit machine


struct A
{
    uint32_t var1;
    uint32_t var2;
    uint32_t var3;
    uint32_t var4;
    uint32_t var5;
};

In the above structure compiler does not pad and allocates 20 bytes.

now we have another structure which contains one 8 byte variable instead of two 4 bytes.In this case compiler pads and allocates 24 bytes to this structure.

struct B
{
    uint32_t var1;
    uint32_t var2;
    uint32_t var3;
    uint64_t var5;
};

why there is such behaviour? If compiler align the data into 8 byte boundry then there should be padding of 4 bytes in the 1st structure and should not pad the 2nd structure in such case. and also if compiler align the data into the 4 byte boundry then why there is padding of 4 byte in the 2nd structure ?

compiler: GCC Platform: 64 bit linux , x86_64


Solution

  • The rule for alignment (on x86 and x86_64) is generally to align a variable on it's size.

    In other words, 32-bit variables are aligned on 4 bytes, 64-bit variables on 8 bytes, etc.

    In your second case, 4 bytes of padding are added between

    uint32_t var3;
    uint64_t var5;
    

    to get var5 to align on 8 bytes.

    For this reason it is better to order data members from largest to smallest (but it's not that simple due to data locality, readability etc.).