What is the rule of structure padding

Asked by At

I have looked through a post of structure padding in geeksforgeeks, https://www.geeksforgeeks.org/is-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member/ But I don't know why in this case:

int main() 
{ 

    struct C { 
        // sizeof(double) = 8 
        double z; 

        // sizeof(short int) = 2 
        short int y; 
        // Padding of 2 bytes 

        // sizeof(int) = 4 
        int x; 
    }; 

    printf("Size of struct: %d", sizeof(struct C)); 

    return 0; 
} 

I know y (short int) is followed by x (int) and hence padding is required after y. But why the padding here is 2?

1 Answers

1
ybungalobill On

The compiler wants to align int on a four-byte boundary, and it is two-bytes short of that, therefore the padding is calculated as two bytes:

struct C { 
    // offset = 0
    double z; 
    // offset = 8
    short int y; 
    // offset = 10
    // ... padding ...
    // offset = 12
    int x; 
    // offset = 16
}; 

The next multiple of four greater than 10 is 12.

EDIT: The structures are, in practice, aligned following this algorithm (pseudocode):

offset = 0;
alignment = 1;
for each field in structure {
    offset = (offset + field.alignment - 1) / field.alignment * field.alignment;
    field.offset = offset;
    alignment = lcm(alignment, field.alignment);
}
structure.alignment = alignment;
structure.size = (offset + alignment - 1) / alignment * alignment;