How to get the total memory, used memory, free memory from C++ code on Linux system?
-
1Read the pseudo-files in /proc. They have a manpage. – Chris Stratton Oct 17 '14 at 18:15
-
1Possible duplicate, depending on whether you want system-wide or process-specific information: [How to get memory usage at run time in c++?](http://stackoverflow.com/q/669438/464709) – Frédéric Hamidi Oct 17 '14 at 18:19
2 Answers
Run your program through valgrind
. For a program called foo
, for example:
valgrind foo
It'll run the program in a harness that keeps track of memory use and print out that information after the program terminates.
If you don't have valgrind
installed for some reason, you should be able to find it in your distro's package repository.

- 864
- 5
- 16
As commented by Chris Stratton, you can -on Linux- query a lot of system information in /proc/
so read proc(5); which contain textual pseudo-files (a bit like pipes) to be read sequentially. These are not real disk files so are read very quickly. You'll need to open and close them at every measurement.
From inside a process, you can query its address space in virtual memory using /proc/self/maps
-and /proc/self/smaps
; outside of that process, for another process of pid 1234, use /proc/1234/maps
& /proc/1234/smaps
; you can get system wide memory information thru /proc/meminfo
So try the following commands in a terminal:
cat /proc/meminfo
cat /proc/$$/maps
cat /proc/$$/smaps
cat /proc/self/maps
to understand more what they could give you.
Be aware that malloc
and free
(used by new
and delete
) are often requesting space (from the kernel) using syscalls like mmap(2) but are managing previously free
-d memory to reuse it, so often don't release memory back to the kernel with munmap
. Read wikipage on C memory management. In other words, the used heap is not accessible outside the process (since some unused, but reusable for future malloc
-s, memory remains mmap
-ed). See also mallinfo(3) and malloc_stats(3).
As Justin Lardinois answered, use valgrind to detect memory leaks.
Advanced Linux Programming is a good book to read. It has several related chapters.

- 1
- 1

- 223,805
- 18
- 296
- 547