We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,621 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

How to find memory leak?

 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?

3
Contributors
2
Replies
1 Hour
Discussion Span
1 Year Ago
Last Updated
3
Views
MastAvalons
Light Poster
32 posts since Jan 2012
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 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.

thines01
Postaholic
Team Colleague
2,433 posts since Oct 2009
Reputation Points: 447
Solved Threads: 408
Skill Endorsements: 7

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).

mike_2000_17
21st Century Viking
Moderator
3,135 posts since Jul 2010
Reputation Points: 2,050
Solved Threads: 625
Skill Endorsements: 41

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0575 seconds using 2.67MB