There are many fields in /proc/mem: I know that I can’t just take “MemFree”, because lots of memory is actually cached. So the question is, how can I calculate the amount of free memory?
Assumptions:
- The system is configured with no swap space.
- My definition of “free memory” is that malloc starts failing when this hits zero.
Use the source luke!
free.c — the source for the ‘free’ command line utility
sysinfo.c — see the method meminfo() for an example of how /proc/meminfo is read in.
Whilst reading /proc is pretty straight forward being able to predict whether malloc is going to fail is not at all easy. As others have mentioned issues such as overcommit muddy the issue. The standard approach is to just try and allocate what you need and if you can’t have it fail gracefully or work with less.
This series of articles is worth reading if you have enough time: What every programmer should know about memory.