customized "new" and pointer alignment

Kevin Bealer kevinbealer at gmail.com
Tue Jan 30 00:40:23 PST 2007


%u wrote:
> no answer from digitalmars.D.learn, try it here.
> 
> == Posted at 2007/01/29 15:52 to digitalmars.D.learn
> 
> I want to do explicit memory allocation for some of my objects,
> 
> I'm reading:  http://digitalmars.com/d/memory.html#newdelete
> 
> which says:
> 
> # The pointer returned from new() must be to memory aligned to the default
> alignment. This is 8 on win32 systems.
> 
> Then on the next section:
> 
> http://digitalmars.com/d/memory.html#markrelease
> 
> new(size_t sz)
>     {   void *p;
> 
>  p = &buffer[bufindex];
>  bufindex += sz;
>  if (bufindex > buffer.length)
>      throw new OutOfMemory;
>  return p;
>     }
> 
> Is this code correct? I mean the object size (sz) could be any integer, how
> can one ensure the alignment requirement?
> 
> If the above code in "Mark/Release" is incorrect, can anyone tell me how to
> return aligned memory pointers?  and for lots of small objects, does alignment
> waste too much memory?
> 
> Thanks.
> 

Most allocators align data to the largest primitive excepting perhaps 
'real'.  The malloc() manpage says 'for any data type' which implies at 
least 64 bits, but I'm not sure I would rely on more than 32 bit aligns 
on a 32 bit system.

In the calling code you can align data with something like this, not 
tested btw:

// Allocate sz bytes, aligned to a multiple of aln.

void[] data = new void[sz + aln-1]; // enough bytes to make this work
int shift = (aln - (data.ptr & (aln-1))) & (aln-1);
data = data[shift..sz+shift]; // slice the array at a multiple of al

This assumes 'al' is a power of 2.  I can't imagine why a non-power-of-2 
alignment would be useful, but you could replace "& (x-1)" with "% x" to 
get that.

Kevin



More information about the Digitalmars-d mailing list