views:

183

answers:

5

A friend of mine was asked, during a job interview, to write a program that measures the amount of available RAM. The expected answer was using malloc() in a binary-search manner: allocating larger and larger portions of memory until getting a failure message, reducing the portion size, and summing the amount of allocated memory.

I believe that this method will measure the amount of virtual, not physical, memory. But I got curious about the matter.

Is there a way to tell the amount of available RAM from within the program, without using exec(dmesg |grep -i memory) ?

+5  A: 

You are correct: malloc() makes no distinction between physical or virtual memory. In fact, that's the whole point of virtual memory: to make such details irrelevant to programs.

You can find out but it is OS-specific. For example, Linux.

cletus
Thanks. there's some good info in the procfs - OS dependent, but very useful.
Adam Matan
+3  A: 

The only way to do this is to use some OS-specific functionality. Using malloc() is useless for a number of reasons:

  • it measures virtual memory
  • the OS may well have per-process cap on memory allocations
  • allocating much more memory than is physically available often degrades the platforms stability to the point where "go back one" algorithm suggested in the question probably won't work
anon
+1  A: 

this is OS specific and you should collect such information from the OS services unless you want to make your own memory management layer

A.Rashad
I seriously doubt it.
Adam Matan
A: 

Very OS specific but for Linux the information about system memory is in /proc/meminfo. You can also probably use the sysctl interface (http://www.linuxjournal.com/article/2365) to get this data in a C program.

tonylo
+1  A: 

Using malloc() will only tell you how much memory can be allocated to a single process. There may be reasons why this is lower than the total amount of virtual memory. For instance, you might have OS quota or a per-process 32-bit-limited address space.

(And, of course, virtual memory >= RAM)

MSalters