Your comments seem to indicate that you really want to know, this is a lot of memory that malloc can allocate in a single block. This roughly corresponds to the maximum allowable VM size minus the current virtual machine size. The following code returns:
#include <sys/resource.h> #include <sys/time.h> #include <stdint.h> uint64_t get_total_free_mem() { uint64_t vm_size = 0; FILE *statm = fopen("/proc/self/statm", "r"); if (!statm) return 0; if (fscanf("%ld", &vm_size) != 1) { flcose(statm); return 0; } vm_size = (vm_size + 1) * 1024; rlimit lim; if (getrlimit(RLIMIT_AS, &lim) != 0) return 0; if (lim.rlim_cur <= vm_size) return 0; if (lim.rlim_cur >= 0xC000000000000000ull) // most systems cannot address more than 48 bits lim.rlim_cur = 0xBFFFFFFFFFFFFFFFull; return lim.rlim_cur - vm_size; }
The only exception is that in some cases getrlimit may return 0xFFFFFFFFFFFFFFFF , however, most 64-bit systems cannot address more than 48 bits of the address to use, no matter what. I have explained this, but there may be other cases that I have missed. For example, 32-bit applications usually cannot allocate more than 3 GB of memory, although this depends on how the kernel was built.
The real answer is why you would like to do this. Typically, the maximum amount that malloc can allocate is significantly greater than the amount that the system can actually process. When you call malloc, the system will happily distribute any amount you request (to the AS limit, which usually ends), even if there are no pnhysical or swap available. Until your program tries to write to memory (including writing 0 s), the memory is not actually allocated from physical memory or swap. When you write to this, when the system will work on how to find out where to get the memory, and if you encounter problems.
It is best to use one of the other answers that tells you how much physical memory is available, and never allocate more. Usually less, since you want to leave some physical memory available for other processes and the kernel itself.
source share