I would really like to actually only allocate 64KB of memory, not 128KB and then do the alignment manually - far too wasteful. VirtualAlloc on windows gives precisely this behavior. Supposedly there's code in SquirrelFish for doing this on just about every platform, but I haven't managed to locate it. Is there a space efficient way to allocate 64KB on a 64KB boundary in POSIX? Failing that, in Linux?
+7
A:
Check out posix_memalign(3)
SYNOPSIS
#include <stdlib.h> int posix_memalign(void **memptr, size_t alignment, size_t size);
DESCRIPTION
The posix_memalign() function allocates size bytes of memory such that the allocation's base address is an exact multiple of alignment, and returns the allocation in the value pointed to by memptr.
Check out the manpage for further details...
Steven Schlansker
2010-05-23 08:08:23
That'd work. Of course if it's internally mallocing 128KB, then returning a pointer to somewhere near the middle of it that's aligned on 64KB boundary it'd be unacceptable to me. I'll have to check the source code and see how it's implemented.
Eloff
2010-05-23 19:40:05
The way it's implemented in libc is to malloc(size + 2*alignment) and then find the aligned part in the middle. But it will then attempt to return any dangling head or tail part of the memory to the heap if it's large enough, so it's not actually as wasteful as I feared. It'll work.
Eloff
2010-05-23 20:28:24
A:
You could use mmap() with MAP_PRIVATE. Quite a few libc allocators these days internally use mmap() to get chunks of memory to allocate from.
srparish
2010-05-24 03:08:37
A:
Of course posix_memalign is the elegant solution, but even if you allocate 128k, any untouched pages will remain as copy-on-write zero pages and use minimal physical resources. You could also use mmap with MAP_PRIVATE to make a 128k map, and then munmap whatever parts of it are unaligned.
R..
2010-06-26 10:34:37