Shashi said:
Can somebody explain how the byte alignment for structures work,
taking the following example and considering:
byte of 1 Byte
word of 2 Bytes
dword of 4 Bytes
typedef struct
{
byte a;
word b;
dword c;
byte d;
}foo;
foo foo1;
x=sizeof(foo1);
What will be the value of x in different cases,
For One Byte Alignment
For Two Byte Alignment
For Four Byte Alignment
It will be nice if I get a good explaination too...Thanx
The Standard that defines the C language says little
about alignment. It notes that some implementations may
find it advantageous to align certain data objects to
certain address boundaries, and it permits implementations
to insert extra "padding bytes" after struct elements in
order to satisfy the alignment requirements. It can be
deduced that the alignment for some object is a divisor
of the object's size, but this is not explicitly stated.
"One byte alignment" presumably means that a data
object is properly aligned if its address is divisible by
one, or in other words a data object can begin at any
address. In this case there is no compelling reason for
the implementation to insert any padding in a `foo' struct,
and `sizeof(foo)' is probably 1+2+4+1 = 8 bytes.
"Two byte alignment" presumably means that a data
object is properly aligned if its address is divisible by
two, but that objects smaller than two bytes need no
alignment (because of the divisibility criterion). In
this case there will probably be padding after `a' so that
`b' and `c' can begin on even addresses, and more padding
after `d' so the entire struct takes an even number of
bytes (if its size were odd, you couldn't malloc() an
array containing two of them). So the total is probably
1+1+2+4+1+1 = 10 bytes.
You should now be able to work out the four-byte case,
and I'll leave you the pleasure of doing so (in case this
is homework). The interesting thing about this case is
that we know what alignment is required for `dword' and
for `byte', but "four byte alignment" doesn't tell us how
a `word' must be aligned. The two possibilities lead to
two different likely arrangements of padding bytes, and
you should try to find them both.
Note that I've been saying "likely" arrangements and
"probable" sizes, because the Standard grants quite a lot
of freedom to the implementations in this matter. For
example, an implementation is free to align a struct more
strictly than any of its constituent elements, if that
seems convenient to the implementors; the two-byte case
probably gives a size of 10 bytes, but might plausibly
yield 12 or 16 instead. The only way to be sure is to see
what the implementation actually does -- and to realize
that other implementations may do it differently.