using union to force memory to be aligned

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.
 
A

Alexander Bartolich

myx said:
[...]
My question is why do we have to align the pointer returned by malloc,

Modern hardware accesses RAM through a system of layered caches. Objects
that cross cache boundaries have to be assembled byte wise from multiple
cache lines. CPUs of the i386-family do this silently in the background.
With true RISC architectures unaligned memory access just raises a trap.
and how this alignment reached using such trick?

The compiler will insert padding bytes to align data structures, if
necessary. This includes bytes at the end of a struct to guarantee
that you can build arrays from it.
 
M

myx

Richard said:
It then farms out sections of this pool, and *each section* must be properly aligned

I seem to understand now. I thought they use the "trick" to somehow
align the pointer, returned by sbrk (which is propably not aligned).
So, this function wouldn't return an aligned pointer, if the sbrk()
returns not aligned pointer, would it?

Thanks all for your detailed answers, they were usefull for
understanding too.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top