On Sun, 11 Nov 2007 19:00:07 -0800, somenath <so*********@gm ail.com>
wrote:
>
Hi All,
I have one question regarding the alignment of pointer returned by
malloc.
This section of the book is not talking about the standard malloc
function. It is talking about the sample malloc function on page 187.
>
In K&R2 page number 186 one union is used to enforce the alignment as
mentioned bellow.
typedef long Align;
union header {
struct {
union header *ptr;
unsigned size;
}s;
Align x;
};
typedef union header Header;
In this author is saying that Align field is never used; it just
forces each header to be aligned on a worst-case boundary.
I am not able to understand how Align field forces the alignment ?
Consider a system with four-byte pointers, two-byte int, and
eight-byte long, each aligned on a multiple of its length and long
being the strictest. The union consists of two members, a struct s
and a long x. The struct consists of two members, a pointer and an
unsigned int. Obviously the struct must be aligned on a four-byte
boundary its sizeof must be a multiple of four. However, there is at
least one type that must be eight-byte aligned. To insure that any
object of type union header is so aligned, the member x of type long
is added to the union. Since x and s start at the same address (at
the beginning of the union), x forces the entire union to be aligned
on a multiple of eight (which is also a multiple of four to satisfy s)
with a sizeof that is also a multiple of eight. They do this because
the address this sample malloc will return is going to be one byte
beyond the end of an instance of this union type. This will insure
that the sample malloc complies with the interface of the standard
malloc in that the returned address is properly aligned for any type
of object.
>According to my understanding alignment of data means storing the data
in proper address as system needs . For example in some system integer
should be stored such that starting address is divisible by power of
2.
But I am not getting how this kind of requirement is enforced by
'Align' .
Please provide some input on this topic.
Remember, the book is 20 years old. On a modern system, long long or
long double may have a stricter alignment requirement than long.
Remove del for email