Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compiler applies structure padding even though it's not needed

I’m trying to understand how structure padding works in C. In particular, in the Linux x86-64 environnement. 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

16

>Solution :

The largest member of struct b 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading