Archived

This topic is now archived and is closed to further replies.

Why does this code leak?

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

Recommended Posts

I am having trouble with the folllowing snippet of code:

{
_pLeaf.push_back( Leaf(this) );
return -(_pLeaf.size());
}

{
_pNodes.push_back( Node(this) );
return _pNodes.size();
}


The fluid studios memory manager reports that this is leaking memory. I can''t understand why. pLeaf and pNodes are both STL vectors, containing objects.

Share on other sites

Any chance its something that gets allocated in the Leaf or Node constructors, and which isn''t getting freed by the destructor?

It could be that the temporary you create and push to the vector is not destructing something that it should.

Share on other sites
The leak is elsewhere. Or Node/Leaf allocate memory they never release. Or they don''t have proper copy constructors/assignment operators.

Share on other sites
I don''t think so, essentially it only holds a pointer to the tree to which it belongs and the std::vector, and I have copy constructors defined, as this was a problem I was having earlier.

Share on other sites
Are you deleteting each of the nodes/leafs when you''re destroiying the tree?

As your vectors holds pointers and not the objects themselves, you need to have something like this in the destructor:
Tree::~Tree(){    std::vector<Tree>::iterator i;    for(i = _pLeaf.begin(); i != _pLeaf.end(); i++) delete (*i);    for(i = _pNode.begin(); i != _pNode.end(); i++) delete (*i);    _pLeaf.clear();    _pNode.clear();}

Share on other sites
Btw, what is it your class is doing? Those functions push a pointer to itself on its own vectors. I don''t get why you do that. If that really is what you''re doing, my proposed destructor could prove pretty dangerous.

Share on other sites
quote:
Original post by CWizard
As your vectors holds pointers and not the objects themselves, you need to have something like this in the destructor:

The vectors hold objects which hold pointers to the tree, yes?

It could also be something like this

"Why does Bounds CheckerTM say that I have memory leaks?
This is not an STL bug. It is an artifact of certain kinds of leak detectors.

In the default STL allocator, memory allocated for blocks of small objects is not returned to malloc. It can only be reused by subsequent allocate requests of (approximately) the same size. Thus programs that use the default may appear to leak memory when monitored by certain kinds of simple leak detectors. This is intentional. Such "leaks" do not accumulate over time. Such "leaks" are not reported by garbage-collector-like leak detectors.
"

• 36
• 15
• 9
• 23
• 10