M
myx
Hi.
I've read K&R example "storage allocator", where they are describing
realisation of a malloc function. Here is a cut of the explanation:
----------------
One problem, which we alluded to in Chapter 5, is to ensure that the
storage returned by
malloc is aligned properly for the objects that will be stored in it.
Although machines vary,
for each machine there is a most restrictive type: if the most
restrictive type can be stored at a
particular address, all other types may be also. On some machines, the
most restrictive type is
a double; on others, int or long suffices.
A free block contains a pointer to the next block in the chain, a
record of the size of the block,
and then the free space itself; the control information at the
beginning is called the ``header.''
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 alignment type, which we have
arbitrarily made a long:
typedef long Align; /* for alignment to long boundary */
union header { /* block header */
165
struct {
union header *ptr; /* next block if on free list */
unsigned size; /* size of this block */
} s;
Align x; /* force alignment of blocks */
};
typedef union header Header;
The Align field is never used; it just forces each header to be
aligned on a worst-case
boundary.
I've read K&R example "storage allocator", where they are describing
realisation of a malloc function. Here is a cut of the explanation:
----------------
One problem, which we alluded to in Chapter 5, is to ensure that the
storage returned by
malloc is aligned properly for the objects that will be stored in it.
Although machines vary,
for each machine there is a most restrictive type: if the most
restrictive type can be stored at a
particular address, all other types may be also. On some machines, the
most restrictive type is
a double; on others, int or long suffices.
A free block contains a pointer to the next block in the chain, a
record of the size of the block,
and then the free space itself; the control information at the
beginning is called the ``header.''
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 alignment type, which we have
arbitrarily made a long:
typedef long Align; /* for alignment to long boundary */
union header { /* block header */
165
struct {
union header *ptr; /* next block if on free list */
unsigned size; /* size of this block */
} s;
Align x; /* force alignment of blocks */
};
typedef union header Header;
The Align field is never used; it just forces each header to be
aligned on a worst-case
boundary.