Click here to Skip to main content
Click here to Skip to main content

Trace Utility for preventing memory leaks

By , 24 Jan 2003
 

Introduction

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 hard-to-find memory leaks that often arise during the production of an application.

So, what we need is an easy utility that detects the memory leaks in place when the application is run. Also, that finds out where exactly the memory leak is and how many bytes of memory is not freed.

Using the code

Mainly, we want 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 ssynchronous with each other; failing to call delete will trigger a memory leak.

#define 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);
          return(ptr);
      };
      
//And for Delete this is supposed to be called.

      void __cdecl operator delete(void *p)
      {
          removeTrace((DWORD)p);
          free(p);
      };
      
      
void Dump()
      {
              // The iterator that walks us through.
          AllocatedList::iterator i;
          DWORD totalSize = 0;
          char buf[1024];

          if(!allocatedList)
              return;

          for(i = allocatedList->begin(); i != allocatedList->end(); i++) {
              sprintf(buf, "%-50s:\t\tLINE %d,\t\tADDRESS %d\t%d NOTFREED\n",
                  (*i)->fileName, (*i)->lineNumber, (*i)->address, (*i)->size);
              printf("%s",buf);
              totalSize += (*i)->size;
          }
          sprintf(buf, 
            "\n-----------------------------------------------------------\n");
          printf("%s",buf);
          if(!totalSize) 
          {
              sprintf(buf,"There are no MEMORY LEAKS\n");
              printf("%s",buf);
          }
          else
          {
              sprintf(buf, "Total UNFREED MEMORY: %d bytes\n", totalSize);
              printf("%s",buf);
          }
      };

For checking the results, we need a helper method that walks us through the memory leaks. Finally, we write a method that shows exactly where the memory is leaking, what is the address, and how many bytes are leaked.

main(){
char *str = "This is a Testing Program";
int len = strlen(str);
char *ptr;
ptr = New char[len+1];
strcpy(ptr,str);
delete ptr;
Dump();
}

Take a look at the main function. Instead of calling new char[len+1];, I am calling New. This will add the trace, and delete will remove the trace.

Hope this one is useful too.

License

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

About the Author

Samar Aarkotti
Web Developer
United States United States
Member
Samar holds a Bachelors degree in computer science from INDIA.
 
He has been doing programming since 12 years using Java,J2EE,JSP,C++,MFC,VC++,ATL,COM, TCP/IP and now with in C#, He is currently exploring speech technology using C#.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: Only works on Win32?memberMandalis27 Jan '03 - 19:36 
Doh!
That is cool.
Well, I guess I will die less dumb Wink | ;-)
Thanks!
GeneralModify your codememberA. Riazi25 Jan '03 - 17:57 
Please comment this line
"And for Delete this is supposed to be called."
in your code.
A. Riazi
 

GeneralRe: Modify your codesussA. Samar25 Jan '03 - 19:01 
code is modified, just forgot to comment that peice of code.
QuestionHow is this better?memberMarc Clifton25 Jan '03 - 12:59 
from what MFC provides in Debug builds?
 
Marc
 
Help! I'm an AI running around in someone's f*cked up universe simulator.
Sensitivity and ethnic diversity means celebrating difference, not hiding from it. - Christian Graus
Every line of code is a liability - Taka Muraoka

AnswerRe: How is this better?memberPJ Arends25 Jan '03 - 13:32 
Because it does not use MFCConfused | :confused:
 
I personally do not have enough knowledge in this area to say if this is a good implementation or not, so I will not rate this article. But I will not dump on it either, just because MFC already provides similiar functionality.
 


CPUA 0x5041
 
Sonork 100.11743 Chicken Little
 
"So it can now be written in stone as a testament to humanities achievments "PJ did Pi at CP"." Colin Davies
 
Within you lies the power for good - Use it!
GeneralThis not an MFC article.memberA. Samar25 Jan '03 - 14:47 
This is just a simple C++ article.

GeneralSo god damn...memberRickard Andersson25 Jan '03 - 11:57 
... good article!!
Now I can move on and use your tip and get lesser leaks! Smile | :)
Thank you so sooo much!
 
Rickard Andersson@Suza Computing
C# and C++ programmer from SWEDEN!

UIN: 50302279
E-Mail: nikado@pc.nu
Speciality: I love C#, ASP.NET and C++!

GeneralRe: So god damn...memberA. Samar25 Jan '03 - 15:18 
thanks you for the comment.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 25 Jan 2003
Article Copyright 2003 by Samar Aarkotti
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid