tags:

views:

341

answers:

4

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.
+5  A: 

I have the feeling you're going down the wrong path. What do you want to do with that information? Do you want to see if you can allocate enough memory for the next operation? If so, you can call malloc and check its return value. If it returns null, the memory wasn't avialable.

Note that memory is a highly dynamic resource. Even your act of opening/closing the /proc filesystem might lead to memory overhead. Even if you somehow do manage to get the amount you could allocate with malloc(), noone can guarantee that the same amount of memory is available the split-second you try to allocate it.

soulmerge
+1  A: 

Try taking a look at the answers to this previous question.

Martin Skøtt
+2  A: 

AFAIK, malloc will overcommit by default on linux, so malloc won't fail when you might expect it to. You won't see things fail until you actually touch the memory you malloced, and the OOM killer may be awakened.

This may be of interest (no idea how accurate it is.)

http://opsmonkey.blogspot.com/2007/01/linux-memory-overcommit.html

but googling around for linux malloc overcommit will likely turn up some interesting stuff.

smcameron
+1  A: 

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.

chillitom