4
votes

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

1
doubles only need to be 4 byte aligned, even though they are 8 bytes in size.Paul R
On linux it is 4-byte aligned, 8-byte with -malign-double compile time option.A Person

1 Answers

4
votes

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.