pusam
pusam

Reputation: 443

memory alignment for structure

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.

Upvotes: 2

Views: 612

Answers (1)

jjlin
jjlin

Reputation: 4703

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));

Upvotes: 1

Related Questions