2

I am having a struct with three fields defined as follows:

struct tmp {
    char *ptr;
    unsigned int data1;
    unsigned int data2;
};

After compiled with GCC on a 64-bit system using Intel sandybridge processor, the sizeof(tmp) returns 24.

To my understanding, the compiler pads 4 bytes to both "unsigned int" fields. However, could it be better if there is no padding and the resulting structure is of size 16?

Imagine if there is an array of such structs, by forcing the struct to have a size of 16 would make sure there is no single struct within the array being split over cache lines, since the cache line size is 64 bytes for Intel SandyBridge processors. Therefore reducing the chance to have two memory accesses to acquire such a struct when looping through the array.

pusam
  • 403
  • 1
  • 4
  • 5
  • 1
    On my 64bit computer, `sizeof(struct tmp)` is 16. – asaelr Feb 13 '12 at 03:51
  • @asaelr Well just proves that you are both working on two different systems :P At the OP I would use #pragma(pack) and force it to 16. But can't say if it really is the best thing to do. Let' see what others also think – Lefteris Feb 13 '12 at 03:57
  • I guess what I did was using sizeof(tmp) instead of sizeof(struct tmp) which gives me 24 instead of 16. Is there a reason why these two statements are different? – pusam Feb 13 '12 at 04:31
  • `sizeof(tmp)` would give you the size of something called `tmp`, which you haven't shown us. – Keith Thompson Feb 13 '12 at 05:13
  • What are `sizeof (char*)` and `sizeof (unsigned int)` on your system? – Keith Thompson Feb 13 '12 at 05:16
  • @pusam Maybe you're used to C++, where struct names have an implicit typedef, so you can say either `sizeof(tmp)` or `sizeof(struct tmp)`. But if you have some other variable named `tmp`, that can still shadow the implicit typedef. – jjlin Feb 13 '12 at 06:14

1 Answers1

1

I don't see why your compiler would want to pad the unsigned int members, assuming you don't have some weird setup where unsigned int isn't 32-bit. On my GCC, I get sizeof(struct tmp) == 16.

What happens if you print out the address of each member? That should help you figure out where the padding is. But in any case, you should be able to get rid of the padding by telling GCC to pack the struct, like this:

struct tmp {
    char *ptr;
    unsigned int data1;
    unsigned int data2;
} __attribute__((packed));
jjlin
  • 4,462
  • 1
  • 30
  • 23