How to find heap memory size of a c++ program under linux platform ?I need heap memory space before the usage of new or malloc and also after that.can anyone help?
#include <malloc.h>
#include <iostream>
int main()
{
//here need heap memory space
unsigned char* I2C_Read_Data= new unsigned char[250];
//get heap memory space After the usage of new
return 0;
}
On Linux you can read
/proc/[pid]/statm
to get memory usage information.See the man page for more details.
Answer by Adam Zalcman to this question describes some interesting details of the heap allocation
You can use the getrlimit function call and pass the
RLIMIT_DATA
for the resource. That should give you the size of the data segment for your program.You can also add heap tracking to your own programs by overloading the
new
anddelete
operators. In a game engine I am working on, I have all memory allocation going through special functions, which attach each allocation to a particular heap tracker object. This way, at any given moment, I can pull up a report and see how much memory is being taken up by entities, actors, Lua scripts, etc.It's not as thorough as using an external profiler (particularly when outside libraries handle their own memory management), but it is very nice for seeing exactly what memory you were responsible for.
Apart from external inspection, you can also instrument your implementation of malloc to let you inspect those statistics.
jemalloc
andtcmalloc
are implementations that, on top of performing better for multithreaded code that typical libc implementations, add some utility functions of that sort.To dig deeper, you should learn a bit more how heap allocation works. Ultimately, the OS is the one assigning memory to processes as they ask for it, however requests to the OS (syscalls) are slower than regular calls, so in general an implementation of
malloc
will request large chunks to the OS (4KB or 8KB blocks are common) and the subdivise them to serve them to its callers.You need to identify whether you are interested in the total memory consumed by the process (which includes the code itself), the memory the process requested from the OS within a particular procedure call, the memory actually in use by the
malloc
implementation (which adds its own book-keeping overhead, however small) or the memory you requested.Also, fragmentation can be a pain for the latter two, and may somewhat blurs the differences between really used and assigned to.
You can try "mallinfo" and "malloc_info". They might work. mallinfo has issues when you allocate more than 2GB. malloc_info is o/s specific and notably very weird. I agree - very often it's nice to do this stuff without 3rd party tools.
Use valgrind's heap profiler: Massif