How do I reserve virtual memory in Linux?
I have an application on Windows that reserves a contiguous block of memory using VirtualAllocEx with the MEM_RESERVE flag. This reserves a block of virtual memory, but does not support it with physical pages or page file blocks. As a result, accessing allocated memory will result in a segfault – but other allocations will not intersect with that virtual memory block.
How do I do the same with Linux using mmap? I did notice this question, but does that really guarantee that 1 GB of physical memory won’t be allocated to my process if I don’t touch the allocated page? I don’t want any bumpy problems.
Solution
I believe you should be able to achieve the same by using PROT_NONE
map anonymous memory. Accessing PROT_NONE
memory will result in a segfault, but the memory area will be reserved and will not be used for any other purpose. If you want to allocate large blocks of memory, add MAP_NORESERVE
to ensure that the default overcommit mechanism does not check your allocations.
PROT_NONE
is typically used for the “protect” page at the end of the stack.