Reputation: 12951
I'm porting a project written (by me) for Windows to mobile platforms.
I need an equivalent of VirtualAlloc
(+friends), and the natural one is mmap
. However there are 2 significant differences.
Addresses returned by VirtualAlloc
are guaranteed to be multiples of the so-called allocation granularity (dwAllocationGranularity
). Not to be confused with the page size, this number is arbitrary, and on most Windows system is 64K. In contrast address returned by mmap
is only guaranteed to be page-aligned.
The reserved/allocated region may be freed at once by a call to VirtualFree
, and there's no need to pass the allocation size (that is, the size used in VirtualAlloc
). In contrast munmap
should be given the exact region size to be unmapped, i.e. it frees the given number of memory pages without any relation about how they were allocated.
This imposes problems for me. While I could live with (2), the (1) is a real problem. I don't want to get into details, but assuming the much smaller allocation granularity, such as 4K, will lead to a serious efficiency degradation. This is related to the fact that my code needs to put some information at every granularity boundary within the allocated regions, which impose "gaps" within the contiguous memory region.
I need to solve this. I can think about pretty naive methods of allocating increased regions, so that they can be 64K-aligned and still have adequate size. Or alternatively reserve huge regions of virtual address space, and then allocating properly-aligned memory regions (i.e. implement a sort of an aligned heap). But I wonder if there are alternatives. Such as special APIs, maybe some flags, secret system calls or whatever.
Upvotes: 3
Views: 3317
Reputation: 157484
If possible, use posix_memalign
(which despite the name allocates rather than aligns memory); this allows you to specify an alignment, and the memory allocated can be released using free
. You would need to check whether posix_memalign
is provided by your target platform.
Upvotes: 1
Reputation: 179717
(1) is actually quite easy to solve. As you note, munmap
takes a size parameter, and this is because munmap
is capable of partial deallocation. You can thus allocate a chunk of memory that is bigger than what you need, then deallocate the parts that aren't aligned.
Upvotes: 6