What is the size of struct?

5 01 2012

In a 32 bits system I have one struct like that :
struct demo {
  int a;
  char b;
  int c;
};

What is the size of this struct (without compiler optimizations)?

9 bytes? Wrong! 12 is the correct answer. Are you surprised?

And if we put one more thing:
struct demo {
  int a;
  char b;
  int c;
  char d;
};

And now? Can you guess the size?

10?? Wrong again… 16!

Ok, one more chance… if I change de order of the elements in the structure? Like this:
struct demo {
  int a;
  char b;
  char d;
  int c;
};

If the last one was 16, so… 16 again?!?! Wrong again! Actually, now the correct answer is 12!

First of all the compiler (gcc) without optimization uses word byte size, so always use a 4x mulpltiplicator value.

So, in the first case, instead of using 9, it uses 12

In the second case, is the same idea, but instead of 10 we have 16, because after the third element we already have 12, plus 1 byte, it jumps to 16.

It works for the third case too.

So, the order of the elements on the structure matters for the struct size.

PS.: if you need memory optimization and it’s important tou you to have the exact size of the struct, on gcc you can compile with -fpack-struct

Did you get it? I hope so…


Actions

Information

Leave a comment