1,105,384 Community Members

How to find memory leak?

Member Avatar
MastAvalons
Light Poster
32 posts since Jan 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

 class A {
   public :
         list< string> getList (){
                list< string> l;
                l.push_back ("str1");
                l.push_back ("str2");
....
          return l;
         }
}

A * a = new A();
list l = a->getList();

I'm working on readymade code, which has a memory leak. How to find exactly where the memory is not freed and there is a leak?

Member Avatar
thines01
Postaholic
2,420 posts since Oct 2009
Reputation Points: 389 [?]
Q&As Helped to Solve: 413 [?]
Skill Endorsements: 10 [?]
Team Colleague
Featured
 
0
 

There are a few tools to do that, but the first thing you should do is see that you are deleting any dynamically created variables when they are no longer necessary.

Member Avatar
mike_2000_17
21st Century Viking
4,085 posts since Jul 2010
Reputation Points: 2,259 [?]
Q&As Helped to Solve: 800 [?]
Skill Endorsements: 73 [?]
Moderator
Featured
Sponsor
 
0
 

Well, from the code you posted, if there is no delete a; after, then there is clearly a memory leak there. How I found that memory leak: I opened my eyes and looked, that's a good trick.

Seriously though, finding memory leaks can be a very difficult if you have a large code-base to plow through.

One great tool for this is Valgrind. I think VS also has decent tools for that, but I haven't tried them.

All in all, the best remedy for memory leaks is prevention. For instance, designing software with ownership relationships in mind.

Another, somewhat desperate, trick is to just make a file-search for the keyword "new" and for each one, make sure it is either immediately wrapped in a smart-pointer (with automatic storage) or that it has a corresponding "delete" (and that any deep-copy or reallocations clean up the old storage correctly).

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: