Win32 memory allocation with large alignment

半城伤御伤魂 提交于 2019-12-01 07:57:45

问题


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?


回答1:


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.




回答2:


Have a look at the source for _aligned_malloc in the windows/MSVC crt, its very simple to use the same method to align virtual memory, i'd would even go so far as to say, just replace its internal malloc call (same goes for _aligned_free), this allows allocation with only a single system call.

However, why do you need such massive alignment? Are you trying to abuse address bit patterns for fast memory block slabs?



来源:https://stackoverflow.com/questions/7616719/win32-memory-allocation-with-large-alignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!