The address of a block returned by malloc
or realloc
in
GNU systems is always a multiple of eight (or sixteen on 64-bit
systems). If you need a block whose address is a multiple of a higher
power of two than that, use memalign
, posix_memalign
, or
valloc
. memalign
is declared in malloc.h and
posix_memalign
is declared in stdlib.h.
With the GNU C Library, you can use free
to free the blocks that
memalign
, posix_memalign
, and valloc
return. That
does not work in BSD, however—BSD does not provide any way to free
such blocks.
The
memalign
function allocates a block of size bytes whose address is a multiple of boundary. The boundary must be a power of two! The functionmemalign
works by allocating a somewhat larger block, and then returning an address within the block that is on the specified boundary.
The
posix_memalign
function is similar to thememalign
function in that it returns a buffer of size bytes aligned to a multiple of alignment. But it adds one requirement to the parameter alignment: the value must be a power of two multiple ofsizeof (void *)
.If the function succeeds in allocation memory a pointer to the allocated memory is returned in
*
memptr and the return value is zero. Otherwise the function returns an error value indicating the problem.This function was introduced in POSIX 1003.1d.
Using
valloc
is like usingmemalign
and passing the page size as the value of the second argument. It is implemented like this:void * valloc (size_t size) { return memalign (getpagesize (), size); }Query Memory Parameters for more information about the memory subsystem.