Boost logo

Boost :

From: Jonathan Wakely (cow_at_[hidden])
Date: 2005-01-20 11:35:26


On Thu, Jan 20, 2005 at 03:29:48PM +0000, Dave Handley wrote:

> > Dave Handley wrote:
> >
> > > My recommendations for things to look at include:
> > >
> > > 1) Allocate using malloc as another creation policy
> >
> > I'm looking at Loki's library and thinking that it has a major bug.
> > Doesn't his implementation have the same alignment problems that my
> > original static allocator did? Wouldn't it be impossible to ensure that
> > memory allocated by malloc was aligned properly?
> >
> > -Jason
>
> Jason,
>
> Other posters have dealt with the fact that malloc and new don't have
> alignment issues, but haven't explained why. Clearly alignment issues
> exist when you have to have a particular variable (like an int)
> sitting on a word boundary. This is an architecture limitation - it
> usually depends on the bus size, since on a 32 bit bus, you would want
> to get an int in a single fetch operation. An issue happens when you
> don't know the type being allocated when you are actually doing the
> allocation. Static memory is allocated by the linker, and the
> standard does not guarantee any form of alignment, except that the
> memory is alignment with the type being allocated. Malloc and New are
> guaranteed to return memory that is aligned for an object of that size

Guaranteed to be aligned for _any_ type, isn't it ?

Quoting POSIX description of malloc(3):

The pointer returned if the allocation succeeds shall be suitably
aligned so that it may be assigned to a pointer to any type of object
and then used to access such an object in the space allocated

And from MSDN:

The storage space pointed to by the return value is guaranteed to be
suitably aligned for storage of any type of object.

And from Glibc:

The address of a block returned by malloc or realloc in the GNU system
is always a multiple of eight (or sixteen on 64-bit systems).

And ISO 14882 on "new" (5.3.4/10):

For arrays of char and unsigned char, the difference between the result
of the newexpression and the address returned by the allocation function
shall be an integral multiple of the most stringent alignment
requirement (3.9) of any object type whose size is no greater than the
size of the array being created. [Note: Because allocation functions are
assumed to return pointers to storage that is appropriately aligned for
objects of any type, this constraint on array allocation overhead
permits the common idiom of allocating character arrays into which
objects of other types will later be placed. ]

jon

> (according to the standard). You can also have similar alignment
> problems if you allocate memory on the stack.

--
"Some men are born mediocre, some men achieve mediocrity,
 and some men have mediocrity thrust upon them."
         - Joseph Heller

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk