Memory leaks in C/C++

I've been programming in C/C++ lately and after hours searching for the origin of some segmentation faults and memory corruptions I started searching for a tool to track my memory usage. Meaning I wanted to know what happened with the new's and if I'm deleting everything.
After a preliminary search I didn't find the right thing I was looking for, a program for linux (ubuntu) 64 bits, easy to use and for free.
Nonetheless I came across an answer to a post suggesting to override the new and delete operations with ones that would allocate/free the memory but also print the number of bytes being allocated/freed to a file.
I tried that but the operations are not that easy to replace, so what I did instead is the following.
First I created a new file stream:
std::ofstream fileMem;
fileMem.open("mem.txt");
fileMem.close();
The open and close commands are at the start and end of the main() procedure respectively. Note that this will replace the file mem.txt every time you run the program.
Then I used the following statements to write to the file what I was doing.
new:
fileMem << "Allocated, <variable name>, " << sizeof(variable type) << std::endl;
delete:
fileMem << "Freed, <variable name>, " << sizeof(variable type) << std::endl;

Under variable type you should put what you use in the new sentence. Something like "int[n]" or "struct list".
You can see that I put ',' in there. So after each run I opened the file mem.txt and copied it to an OpenOffice Spreadsheet where it asked how to separate the data, you can check ',' and it displays "Allocated/Free", <variable name>, <allocated/freed bytes> . I also had a formula which populated the next column with the same value if allocated or the negative value if freed. Then in a box next to it I put the sum of the previous column and voila. If it displays zero you are freeing everything you allocated. If not, you need to look at your code to see where you are forgetting to delete something.
You have to be very careful, I had many errors because I didn't use the correct type in sizeof().
Suggestion: try to comment out the messages for variables you already know you are freeing correctly. I made a progressive analysis, that way it's handier.

It may take some work and you think it's too complicated, but it actually helped me a lot to track down where I was having problems.

Popular posts from this blog

Export to Excel with spreadsheet gem

Caleidoscopio de dos naciones

Keep sidekiq running using monit