On 8/7/2010 7:57 AM, Shao Miller wrote:
> In C99, is it possible to write a well-defined program which
> implements its own memory allocation in an alignment-responsible way,
> without using the C99 memory management functions?
>
> For example, out of some pool with 'static' storage duration? I
> cannot figure out how in any pool of 'unsigned char[XXX]', we could
> determine the alignment for where a pointer might point to.
For any object type T, the required alignment is a divisor
of sizeof(T). In particular, alignment on a sizeof(T) boundary
is always tight enough, perhaps tighter than needed.
Unfortunately, that doesn't seem to help! Since the family
of potential types in C is open-ended (in C99, even the family of
primitive types is open-ended), you can't just make a union of all
possible T and form your pool from an array of union instances.
Your malloc-equivalent could not be 100% sure that the memory
it returned was suitably aligned for all possible types; the caller
might be using a T you hadn't thought of. You could do it for any
one program, perhaps, by cataloging every type the code uses, but
the maintenance headaches would be simply awful.
The dodge of using a big char[] as the basis of the pool (a
theme you seem unhealthily attracted to) is flawed, the fundamental
problem being that there's no portable way to determine how the
array itself is aligned. I think you just need to accept the fact
that some internals of memory management aren't portable.
--
Eric Sosman
lid