How do I get rid of memory leaks?

This topic is 4649 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Well, I've started using Paul Nettle's memory manager (which is excellent, by the way), which has identified plenty of leaks. The problem is, I'm not really too sure about how to fix them, being a bit rubbish at C++ :) Take, for example, this bit of code:
SomeClass::AddThingsToList() {
list.push_back(new OtherClass());
list.push_back(new OtherClass());
list.push_back(new OtherClass());
}

How on earth do I go about freeing up the memory from the new OtherClasses? Do I do it on program exit by using list.erase()? That's how I thought it would work, but it's still reporting that the allocations made on these lines aren't being deallocated. What about deleting things like singletons? I'm using the singleton class from Richard Fine's Enginuity series, which works wonderfully, except that calling Whatever::Destroy() or Whatever::GetSingleton().Destroy() still reports that the memory hasn't been deallocated. The Destroy method deletes the reference to the singleton and sets it to 0. What am I doing wrong? Thanks in advance for your help, folks, you're a jolly helpful bunch :)

Share on other sites
*Hugs smart pointers and runs away to hide somewhere*

Well I'd assume(now this is a tired post and I'm bound to be wrong) that you just do delete list; or something of the sort.

Actualy come to think of it I'm almost posotive that's 100% wrong.

Share on other sites
For the STL containers I just iterate through the list and SAFE_DELETE() (or whatever is appropriate) them before clearing/erasing the contents.

hth
Jack

Share on other sites
As far as the standard containers go, they don't know that they're storing pointers per se, and so won't delete that memory for you. Rather than using erase(), you'll need to delete them manually, like 'delete *iter' or something similar. You could also use a smart pointer class that will handle the cleanup for you.

Share on other sites
Suggestions:

    std::container< T * >=>  std::boost::ptr_container< T * >=>  std::container< boost::shared_ptr< T * > >=>  std::container< T * boost::variant< T1, T2, ..., TN > >

Share on other sites
A jolly good idea, MaulingMonkey, though the download link on the Boost homepage isn't working at the moment. Is there a (trustable) mirror I can use?

Share on other sites
Quote:
 Original post by hymermanA jolly good idea, MaulingMonkey, though the download link on the Boost homepage isn't working at the moment.

Now it is!!!

1. 1
Rutin
46
2. 2
3. 3
4. 4
5. 5
JoeJ
18

• 13
• 10
• 12
• 10
• 13
• Forum Statistics

• Total Topics
632998
• Total Posts
3009802
• Who's Online (See full list)

There are no registered users currently online

×