sizeof structure not expected in C as compiler does not add padding
c, sizeof, struct
Solution
On Linux, unless you pass `-malign-double` to the compiler, doubles are only aligned at 4 byte boundaries, so the struct will not require extra padding.
See documentation here.
Problem
First up, I tried to go through the existing threads in stackoverflow regarding my question. Atleast, I was not able to find a thread which talks about my issue. I am executing the following code for a 32 bit machine through ``` gcc -m32 -o size32 size.c ``` To the contrary, I find that the compiler is not adding the extra padding. I have not added the attribute flag. So I expect the compiler to pad extra bytes. Here is my issue. ``` struct s{ char c; int i; double d; void *p; }; struct s temp; void *q; double d1=10; printf("size of struct = %d sizeof q = %d sizeof double = %d\n",sizeof(temp),sizeof(q),sizeof(d1)); ``` The output was size of struct = 20 sizeof q = 4 sizeof double = 8 This is my calculation. char(1 byte) + 3 bytes padding + int(4 bytes) + double(8 bytes) + (void*)(4 bytes) which is equal to 20 bytes plus 4 bytes due to the longest member alignment rule ( here double is 8 bytes, so struct should be aligned on a 8 byte boundary ) which finally sums to 24 bytes. So total size should be 24 bytes. Why is it showing only 20 bytes? Thanks Chid