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 yields
address sizes : 42 bits physical, 48 bits virtual
address sizes : 42 bits physical, 48 bits virtual
address sizes : 42 bits physical, 48 bits virtual
address sizes : 42 bits physical, 48 bits virtual
address sizes : 42 bits physical, 48 bits virtual
address sizes : 42 bits physical, 48 bits virtual
address sizes : 42 bits physical, 48 bits virtual
address sizes : 42 bits physical, 48 bits virtual
on 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:
00020000-000204ff /usr/bin/executable
00030000-0003ffff [heap]
7ff80000-7ff9ffff [stack]
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 someone LD_PRELOAD
s another malloc
implementation.