The following is an excerpt from a code sample in K&R's The C Programming Language (section 8.7):
typedef long Align;
union header {
struct {
union header *ptr;
unsigned size;
} s;
Align x;
};
typedef union header Header;
And here is the explanatory excerpt:
To simplify alignment, all blocks are multiples of the header size, and the header is aligned properly. This is achieved by a union that contains the desired header structure and an instance of the most restrictive type, which we have arbitrarily made a long.
So, as I understand it, the idea is to ensure that a header
instance takes up a number of bytes that is a multiple of sizeof(Align)
. The goal makes perfect sense to me.
But consider the case where long
is 64 bits, int
is 32 bits, and a pointer is 64 bits. In that case, header.s
will be 64+32 = 96 bits. Thus, sizeof(header)
will be 96 bits, which is not a multiple of 64 as intended.
In such a case, I suppose it would be necessary to define Align
as something else (perhaps double
). But I'm not quite sure whether I'm fully understanding what would dictate that choice for a particular architecture. Is it just the "biggest" type? And what if long
is the biggest type - couldn't it fail to work in the way I described above?
Thanks