Alex Rivera | Logout

Memory alignment in C-structs

Asked 2011-03-25T17:14:31.867
61

I'm working on a 32-bit machine, so I suppose that the memory alignment should be 4 bytes. Say I have this struct:

typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
} myStruct;

The plain added size is 6 bytes, and I suppose that the aligned size should be 8, but sizeof(myStruct) returns me 6.

However if I write:

typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
    int i;
} myStruct;

the plain added size is 10 bytes, aligned size shall be 12, and this time sizeof(myStruct) == 12.

Can somebody explain what is the difference?

Edit
Report

3 Answers

13

By default, values are aligned according to their size. So a 2-byte value like a short is aligned on a 2-byte boundary, and a 4-byte value like an int is aligned on a 4-byte boundary

In your example, 2 bytes of padding are added before i to ensure that i falls on a 4-byte boundary.

(The entire structure is aligned on a boundary at least as big as the biggest value in the structure, so your structure will be aligned to a 4-byte boundary.)

The actual rules vary according to the platform - the Wikipedia page on Data structure alignment has more details.

Compilers typically let you control the packing via (for example) #pragma pack directives.

answered 2011-03-25T17:20:25.530
2

The reason for the second sizeof(myStruct) being 12 is the padding that gets inserted between v3 and i to align i at a 32-bit boundary. There is two bytes of it.

Wikipedia explains the padding and alignment reasonably clearly.

answered 2011-03-25T17:17:33.427
0

Sounds like its being aligned to bounderies based on the size of each var, so that the address is a multiple of the size being accessed(so shorts are aligned to 2, ints aligned to 4 etc), if you moved one of the shorts after the int, sizeof(mystruct) should be 10. Of course this all depends on the compiler being used and what settings its using in turn.

answered 2011-03-25T17:21:05.983

Your Answer