tags:

views:

310

answers:

4
+22  A: 

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

For example:

struct foo_t {
    int x;
    char c;
};

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

Michael Burr
+1, although aligning to 6 bytes sounds weird. Maybe I am a bit behind in low-level stuff, though.
Michael Krelin - hacker
Well, the name starts at offset 4 (plausible enough) and extends to 34. 34 is not a multiple of 4 so it's end-padded to 36, which is 9*4. Makes sense to me!
Carl Smotricz
Its aligning to 32bit boundaries (4,8,16,24,32,36,...)
Mordachai
It is not aligning to 6 bytes. int is taking 4 bytes and char[30] is taking 32 bytes, both multiples of 4 making the size of the structure also a multiple of 4 bytes.
Sinan Ünür
Ah, that makes perfect sense.
Michael Krelin - hacker
The 6-byte alignment is likely a coincidence - 36 is a multiple of 4.
Michael Burr
Also of note: the compiler can insert padding *between* members, too, not just at the end, e.g. `struct { char c; int x; }` will also have size 8 on most 32-bit systems.
Adam Rosenfield
+1 or mentioning arrays since that's the biggest reason for certain platforms
Jim Buck
While I know that it is faster to answer than to search up the duplicates, you had to expect that this has been asked and answered before.
dmckee
A: 

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

avp
+1  A: 

As mentioned, the C compiler will add padding for alignment requirements. These requirements often have to do with the memory subsystem. Some types of computers can only access memory lined up to some 'nice' value, like 4 bytes. This is often the same as the word length. Thus, the C compiler may align fields in your structure to this value to make them easier to access (e.g., 4 byte values should be 4 byte aligned) Further, it may pad the bottom of the structure to line up data which follows the structure. I believe there are other reasons as well. More info can be found at this wikipedia page.

Daniel Brotherston
A: 

Your default alignment is probably 4 bytes. Either the 30 byte element got 32, or the structure as a whole was rounded up to the next 4 byte interval.

Liz Albin