Seems posix_memalign
let you choose a customized alignment
,but when is that necessary?
malloc
has already done the alignment work internally.
UPDATE
The exact reason I ask this is because I see nginx does this,ngx_memalign(NGX_POOL_ALIGNMENT, size, log);
,here NGX_POOL_ALIGNMENT
is defined as 16
, nginxs.googlecode.com/svn-history/trunk/src/core/ngx_palloc.c
The only benefits of posix_memalign
, as far as I can tell, are:
N
bits of a pointer zero so you can store an N
-bit integer in the low bits. :-)Basically, if you need tougher alignment than malloc will give you. Malloc generally returns a pointer aligned such, that it may be used with any of the primitive types (often, 8 bytes on common desktop machines).
However, sometimes you need memory aligned on other boundaries, for example 4K-aligned, etc. In this case, you would need memalign
.
You would need this, for example,
Various hardware may have alignment requirements which malloc
cannot satisfy. The Linux man page gives one such example, I quote:
On many systems there are alignment restrictions, e.g. on buffers used for direct block device I/O. POSIX specifies the pathconf(path,_PC_REC_XFER_ALIGN) call that tells what alignment is needed.
A couple of uses:
Some processors have instructions that will only work on data that is aligned on a power of two greater than or equal to the buffer size - for example bit reverse addressing instructions used in ffts (fast fourier transforms).
To align data to cache boundaries to optimize access in multiprocessing applications so that data in the same cache line isn't being accessed by two processors simultaneously.
Basically, if you don't need to do absurd levels of optimizations and/or your hardware doesn't demand that an array be on a particular boundary then you can forget about posix_memalign.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With