In K&R2 they implement memory allocator in chapter 8. For each block there is header defined something like this (from memory, code may be non-exact):
union header_t
{
struct
{
unsigned size;
unsigned* next;
};
long align;
};
They do this to “make sure that the header is properly aligned on the boundaries of long”. But doesn’t the union align by the largest member? The struct is larger than the single align member, so the header will be aligned on the struct’s multiples anyway, no?
What about when the struct is even larger (say it has many members). Is this alignment union trick always required in when write a memory allocator?
“The struct is larger than the single align member”.
First, says who? What if, on your implementation,
unsignedandunsigned*are each 32 bits, andlongis 128 bits (or more realistically, 16 bits and 64 bits)?Second, so what? Even if the struct is at least as big as
long, it doesn’t mean that it must have at least as big an alignment aslong. Ifunsignedandunsigned*have no alignment requirements, then the struct has no alignment requirements. But perhapslongdoes.