Why does this code leak?

Started by
5 comments, last by jamessharpe 21 years, 2 months ago
I am having trouble with the folllowing snippet of code:
  
int Tree::addLeaf()
{
        _pLeaf.push_back( Leaf(this) );
        return -(_pLeaf.size());
}

int Tree::addNode()
{
        _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.
Advertisement

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.
The leak is elsewhere. Or Node/Leaf allocate memory they never release. Or they don''t have proper copy constructors/assignment operators.
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.

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();}


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.

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

This topic is closed to new replies.

Advertisement