4

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

CHID
  • 1,625
  • 4
  • 24
  • 43

1 Answers1

4

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.

James
  • 24,676
  • 13
  • 84
  • 130
  • I doubt that that applies to Linux in general; I'd expect it to depend on the target CPU and its ABI. – Keith Thompson Jan 13 '14 at 17:06
  • 1
    Yes, see [this answer](http://stackoverflow.com/a/11110283/233201) for a complete discussion of when double is aligned 4 vs. 8 bytes. – James Jan 13 '14 at 17:07