This code detects memory leaks in embedded VC++ almost the same way crtdbg does in VC++. At the end of program execution it will display in the debug window if there were any memory leaks and how the memory looks so you can identify where your memory leak occurred. It will display in the debug window a message saying no memory leaks detected if there are no memory leaks. Similar to what crtdbg.h does in VC++. The code detects memory leaks generated with calls to new and delete operators in C++. The code doesn't detect memory leaks generated with C functions:
free, but that can be done in the future. Let me know and I will program it.
There are 3 simple steps in order to enable memory leak detection:
- Define _DEBUG
- Include "crtdbg.h"
- Let your first line in the code be:
Tips on debugging:
Although it doesn't display the line where the memory leak occurred (read Tip 2), the utility display the address in hex, and you can add a small code to the operator new function, just after the first
if (retPtr == (void*)0x76DA0)
dumb instruction; <- place a breakpoint on this one
so you can detect easily which line of your code called the operator new to allocate memory at the specified address and wasn't freed.
Here's a trick that allow you to get the correct line and filename where the memory leak occurred. Define the following line in every file, or define it in a header file and include it in every file where you want accurate line and filename:
#define new new(_T(__FILE__), __LINE__)
What the code actually does is override the global operator
new that besides allocating memory, it retains the pointer to the allocated memory in a list. The operator delete simply releases memory and deletes the reference to that memory from the list. In the end of the program execution, all the pointers still in the list simply mean memory leaks, and they are displayed in the debug window.
_CrtSetDbgFlag (ON); simply declares an instance of garbageCollector. It has to be the first line of your code, to insure it is the last variable in your program to be destroy, as in its destructor it performs checking of the pointer list and it displays memory leaks. So its destructor must be the last destructor called.
Please report any bugs to Ciprian_Miclaus@yahoo.com. You can use and distribute this code freely, but please keep these few lines. If you make any improvements, or have any ideas about how this code could be improved or just you feel you need to comment this code in any way, please send your comments, idea, improvements to me to my email above.