Home > database >  Compiler applies structure padding even though it's not needed
Compiler applies structure padding even though it's not needed

Time:11-27

I'm trying to understand how structure padding works in C. In particular, in the Linux x86-64 environment. To this end, I re-arranged the order of the members of a given structure to see if the padding won't be applied when it's not needed. However, when I compiled and run the code printing the size of each structure, padding was applied to both of them, even though the second structure (struct b) has its members arranged in such a way that contiguously storing them in memory won't result in one of them occupying multiple word blocks.

#include <stdio.h>

struct a {
    int ak; 
    char ac; 
    char* aptr; 
};

struct b {
    char* bptr;
    int bk;
    char bc;
};



int main(int argc, char* argv[]) {
    printf("%lu\n", sizeof(struct a));
    printf("%lu\n", sizeof(struct b));
}

Output:

16

16

CodePudding user response:

The largest member of struct b (or more accurately, the member with the widest alignment requirements) has 8 byte alignment, so the size of the struct needs to be a multiple of 8 so that an array of that struct will have its members properly aligned.

So struct b will have 3 bytes of padding at the end.

  • Related