2

Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?

I created a Struct randomly and the size of it surprised me because the result does not equal to my calculation:

int main( int argc, char ** argv ) {
    struct S
    {
        int i;
        int b;
        int c;
        long int e;
    };
    cout << sizeof (struct S) << endl; //sizeof is still an operator
    return 0;
}

Normally, 3*int + 1*long int = 3*4 + 8 = 20.

However, the result is 24.

Where are this 4 bytes comes from?

Community
  • 1
  • 1
zeroliu
  • 990
  • 2
  • 10
  • 15

1 Answers1

5

Your struct is padded by four bytes, presumably to place long int on the 8-byte boundary to speed up access to it. This is platform-dependent: not all compilers will add these bytes.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Do you mean 8 rather than 4? (And no, it wouldn't.) – Kerrek SB Sep 27 '12 at 15:52
  • @KerrekSB From http://stackoverflow.com/a/119128/1538531: "One can minimize the size of structures by putting the largest data types at the beginning of the structure and the smallest data types at the end of the structure (like structure Z in the example above)." – Derek Sep 27 '12 at 15:54
  • 1
    @Derek Won't make any difference in this case (if the compiler decides that a long has alignment 8 then the same is true for the whole struct even/in particular when the long is the first data member, and so the size will be padded to 24 so that the invariant regarding the relationship of alignment in arrays and sizeof holds). – Seg Fault Sep 27 '12 at 15:57
  • @Derek In this example you'd still need 4 bytes to align that last int – nullpotent Sep 27 '12 at 15:58
  • Thanks everyone! So in some cases you can minimize the size of structs? – Derek Sep 27 '12 at 15:59
  • Thanks for the quick response, these are very helpful. – zeroliu Sep 27 '12 at 16:05
  • 2
    @Derek In e.g. `struct foo { char a; long b; char c; long d; int e; };` you will probably get padding after both of the `char`s and the `int`, for a total of `7 + 7 + 4 = 18` bytes of padding (if `long` is 8 bytes and `int` 4), while `struct bar { long b, d; int e; char a, c; };` would only get 2 bytes of padding at the end needed to make the size a multiple of 8. That's the point of ordering by data size. – Daniel Fischer Sep 27 '12 at 16:05
  • @DanielFischer Didn't realize we can do this. Great example! – zeroliu Sep 27 '12 at 16:10