cmemorymemory-pool

What does posix_memalign/memalign do


I'm trying to understand what functions memalign() and posix_memalign() do. Reading the available documentation didn't help.

Can someone help me understand how it works and what is it used for? Or, perhaps provide a usage example?

I'm trying to understand how linux memory works, I need to write my own simple memory pool (low-fragmentation heap).


Solution

  • Whereas malloc gives you a chunk of memory that could have any alignment (the only requirement is that it must be aligned for the largest primitive type that the implementation supports), posix_memalign gives you a chunk of memory that is guaranteed to have the requested alignment.

    So the result of e.g. posix_memalign(&p, 32, 128) will be a 128-byte chunk of memory whose start address is guaranteed to be a multiple of 32.

    This is useful for various low-level operations (such as using SSE instructions, or DMA), that require memory that obeys a particular alignment.