I am trying to decide if I should use memalign() over malloc() because aligned memory would make my job easier. I read the GNU documentation here (http://www.gnu.org/software/libc/manual/html_node/Aligned-Memory-Blocks.html) which mentions that The function memalign works by allocating a somewhat larger block. I want to know the exact value for that "somewhat larger block".
Logically thinking the extra memory required should be equal to the the value of alignment required. But I am not sure if there is an optimization over that.
Posix is a standard, not a specific set of code, but we can look at libc for an example.
Here's what posix_memalign() initially allocates in that implementation.
mem = malloc (size + 2 * alignment);
With this beautiful ASCII illustration.
/*
______________________ TOTAL _________________________
/ \
+---------------+-------------------------+--------------+
| | | |
+---------------+-------------------------+--------------+
\____ INIT ____/ \______ RETURNED _______/ \____ END ___/
*/
It then returns to the heap the unused storage on either end of the allocation.
This means that fragmentation may get worse, though the heap memory used is the same amount.
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