Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reserve virtual memory in Linux?

I have an application that reserves a contiguous memory block using VirtualAllocEx on Windows with the MEM_RESERVE flag. This reserves a virtual memory block, but does not back it with a physical page or page file chunk. Hence, accessing the allocated memory will result in a segmentation fault -- but other allocations will not intersect with this virtual memory block.

How can I do the same for Linux with mmap? I did notice the answer in this question, but does that really guarantee that say, 1 GB of physical memory won't be allocated to my process if I don't touch the allocated pages? I don't want any thrashing problems.

like image 559
Matt Fichman Avatar asked Mar 07 '13 01:03

Matt Fichman


1 Answers

I believe you should be able to achieve the same by mapping anonymous memory with PROT_NONE. Accessing PROT_NONE memory will result in a segfault, but the memory region will be reserved and not used for any other purpose. If you want to allocate a very big chunk of memory, add MAP_NORESERVE to ensure that the default overcommit mechanism won't check your allocation.

PROT_NONE is commonly employed for "guard" pages at the end of stacks.

like image 172
nneonneo Avatar answered Nov 20 '22 19:11

nneonneo