I need to allocate large regions of memory (megabytes) with large alignments (also potentially in the megabyte range). The VirtualAlloc family of functions don't seem to provide options to do this.
What I do on Linux to achieve this is to mmap a larger region - large enough to guarantee that a sufficiently large region with the required alignment will be contained in it - and then munmap the regions at the beginning and the end of the large region that are not needed.
As an example, let's say I need 4 megabytes, aligned on a 1 megabyte boundary (i.e. the start of the region having zeroes in the lowest 20 bits). I'd mmap 5 megabytes. Let's say I get the region 0x44ff000-0x49ff000. Within that region is contained the region 0x4500000-0x4900000, which is aligned on a 1 megabyte boundary. I would then munmap 0x44ff000-0x4500000 and 0x4900000-0x49ff000.
Can I do something similar on Win32? If I use VirtualProtect with PAGE_NOACCESS, will the memory be freed? Is there a better solution?
Yes, you can use the same technique. VirtualAlloc
a large range as MEM_RESERVE
. Find the sub-range that is appropriately aligned and call VirtualAlloc
a second time on the sub-range with MEM_COMMIT
.
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