As the title asks,
Is it possible to know the currently available virtual memory (which is allocatable by malloc/mmap) inside an application by programmatically?
What I'm looking for is some kind of a function
unsigned int free_mem();
which will return the size of memory allocatable by malloc or mmap.
Since you are explicitly talking about available virtual memory, you need to find the parts of the virtual address space which are currently unallocated. Segment information is available in
proc/self/smaps
.However, the size of the virtual address space is determined by the cpu your program is executing on. This is not 64 bits on a 64 bit processor, but can be determined by
cat /proc/cpuinfo | grep "address sizes"
which yieldson the VM I am currently testing it on.
Note that the total amount of available virtual address space is different from the largest amount allocatable in one go, since you can only mmap a sequential amount of memory.
For example consider the simple case of 32 bit pointers with the following segments:
In this case the largest continuous segment is
7ffA000-ffffffff
, but the total amount of available virtual memory is only slightly less than 4 GB.Note also that
malloc
may be able to satisfy your request without requiring more virtual memory by reusing already requested pages. The amount available this way depends on a many things (size of the allocation or allocations, state of the heap) and cannot be queried in any portable way. This holds double if someoneLD_PRELOAD
s anothermalloc
implementation.