Writing our own trace utility is much important for complicated and complex applications. This is useful since C++ does not have the concept of GC (garbage collector) unlike C# or Java which automatically takes care of those issues. A good trace file can help a lot if you are trying to find bugs or hard to find memory leaks that often raise during the production of the application.
So what we need is an easy utility that detects the memory leaks in place when the application is run. That also finds out where exactly the memory leak are and how many bytes of memory are not freed.
Using the Code
Mainly, we wanted to rewrite the
new function so that whenever
new is called, it adds the trace and of course for
delete, we have to remove the trace. Both the methods should be synchronous with each other. Failing to call
delete will trigger memory leak.
#define DEBUG_NEW new(__FILE__, __LINE__)
inline void * __cdecl operator new(size_t size,
const char *fileName, int lineNumber)
void *ptr = (void *)malloc(size);
addTrace((DWORD)ptr, size, fileName, lineNumber);
delete, this is supposed to be called:
void __cdecl operator delete(void *p)
For checking the results, we need a helper method that walks us through the memory leaks:
DWORD totalSize = 0;
for(i=allocatedList->begin(); i!=allocatedList->end(); i++)
"%-50s:\t\tLINE %d,\t\tADDRESS %d\t%d NOTFREED\n",
totalSize += (*i)->size;
sprintf(buf,"There are no MEMORY LEAKS\n");
"Total UNFREED MEMORY: %d bytes\n",
I have used a
List to iterate walk the elements.
char *str = "This is a Testing Program";
int len = strlen(str);
ptr = DEBUG_NEW char[len+1];
Take a look at the
main function: instead of calling
new char[len+1]; I am calling
DEBUG_NEW. This will add the trace and
delete will remove the trace.
I still can't find out if there was a way to call
new instead of
This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.
A list of licenses authors might use can be found here.