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?

Recommended Answers

All 2 Replies

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.