C++ - Object Heap Marker to Detect Memory Leaks

In this post I have a program which generates core and from the core file we can find out how many objects for a particular class has been created. This helps in isolating memory leaks related issues. Using this method we can analyze release mode core dumps so as to see the values within each objects.

The basic idea is to put a heap marker string along with each object so that we can identify the object start and end by going through the core dump. What I am doing here is create an array within the class which will have a predefined string so as to identify the object. Now whenever we create that object it gets persisted into heap and at any time we dump the heap we can see that string in heap thereby identifying the start and end of an object. I have tested all these in redhat linux 8.0.

Here is the Class which has markers



#define MARKERSIZE 5
#define BEGMARKER "<A>"
#define ENDMARKER "</A>"
#include <iostream>
class A
{
char beginA[MARKERSIZE ];
int i;
char b;
char endA[MARKERSIZE];

public:
A() : i(0xabcd), b('X')
{
std::cout << "CTOR" << std::endl;
strcpy(beginA,BEGMARKER);
strcpy(endA,ENDMARKER);
}

~A()
{
std::cout << "DTOR" << std::endl;
}

void displayme()
{
printf("ADDR BEG = %p\n",beginA)
printf("ADDR I = %p\n", &i);
printf("ADDR B = %p\n", &b);
printf("ADDR END = %p\n",endA)
}
}


Now the main function which create 10 such objects and generates a core. After which we will analyze the core file to say how many objects for class A got created


#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <A.hpp>

int main()
{
for(int i=0 ; i<10 ; ++i)
{
A *a = new A();
//a->displayme();
//delete a;
}

//send a SIGSEGV signal to generate core
pid_t pid = getpid();
kill(pid,11);
}

Before running the program make sure that you have set the ulimit properly to generate core dumps.
 
-bash-2.05b# ulimit -c unlimited
-bash-2.05b# ./a.out > /dev/null
Segmentation Fault (core dumped)
-bash-2.05b# od –c core.1233| grep "< / A >"|wc –l
11


Here the count is showing as 11 because core also has the string literal entry for ENDMARKER. So 11 – 1 = 10. Just by going through the core file we are able to tell how many objects of A reside in memory.

Now using od itself you can analyze the objects and figure out the values which got populated into the object. While going through the values within the object make sure you take care of the endianess.

Labels: , , ,


About this entry