4-byte alignment shows up in more places than just the stack, too. If you declare a struct like this
Code: Select all
struct Blah
{
short one;
int two;
char three;
};
Then on most 32 bit platforms, the size of the entire struct will be 12 bytes. What happens is that because the int needs 4 bytes, it automatically aligns it on a 4-byte boundary (this is faster). So it adds 2 more bytes of empty padding after the 2-byte short. The size of the entire struct is also padded up to the next 4 bytes, which adds another 3 empty bytes after the char. So the real struct is laid out like this:
Code: Select all
struct Blah
{
short one;
char padding1[2];
int two;
char three;
char padding2[3];
};
The general rule with respect to any kind of value is that its first byte must always be located on an address that is a multiple of its own size. So if you have a struct with 2 shorts it will be 4 bytes and not 8, and 4 chars will also be 4 bytes and not 16. But 2 chars in a struct will also make it 4 bytes, because the size of the struct itself is always a multiple of 4.
To take advantage of this, if you ever use values that are less than 4 bytes in size, you should try to always use them in pairs or quads, so that they fill up the space most efficiently without padding.