I'd like to count number of memory allocation calls (malloc, calloc, new ...) in my program. The program actively uses STL containers. The main purpose is to count memory allocations inside all these containers. I will use this information to optimize performance later. My program is written on C++ and runs under Linux. Are there any tools to do it?
3 Answers
You can overload operator new:
#include <stdlib.h> int numOfHeapAllocations = 0; void* operator new(size_t size) { numOfHeapAllocations++; return malloc(size); } Just put it the first thing in your main file.
1 Comment
operator delete, since operator new is not required to use malloc (though for most systems it seems it does use malloc).You could redefine the operators you want to count.
Example: How to use operator new to count number of times of dynamic memory allocation
1 Comment
Here's something I whipped up in my C++ development environment for linux. you might need to change iostream to stdio.h and cstdlib to stdlib.h (and possibly std to match windows name spaces) to make it work in windows.
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <iostream> #include <cstdlib> static char **ms; using namespace std; class frag{ public: int xyz; }; int numsegments(char** segs){ return strlen((const char*)segs)/sizeof(char*); } void randomfunction1(){ ms[numsegments(ms)]=(char*)malloc(100); } void randomfunction2(){ ms[numsegments(ms)]=(char*)calloc(1,100); } void randomfunction3(){ ms[numsegments(ms)]=(char*)new frag(); //storing class as flat data in memory int segct=numsegments(ms); // get segments frag* init=(frag*)ms[--segct]; // subtract 1 from segment count before reading init->xyz=1; // set variable in class } int main(int argc, char *argv[]){ ms=(char**)calloc(1,1000); //store up to 1000 indexes printf("Segments used so far: %d\n",numsegments(ms)); randomfunction1(); randomfunction2(); randomfunction3(); int total=numsegments(ms); printf("Segments used total: %d\n",numsegments(ms)); int lastsegment=total-1; frag* y=(frag*)ms[lastsegment]; //convert to class printf("xyz in class = %d\n",y->xyz); for (int i=0;i<total;i++){free(ms[i]);} //free all segments free(ms); return 0; } I understand its complex but the basic idea of this program is to allocate a chunk of memory to store pointers to memory fragments then allocate whatever for each fragment then use strlen() to quickly count the fragments. I know you count them as allocations, but I call them fragments.
malloccalls then the simplest way would be to write a wrapper for it - see this question.glibc) that prints information out each timemallocis called. You can use similar code to just increment a global counter.