Skip to main content
gamedev.net
🔒 Locked

Why does this code leak?

Started by jamessharpe Feb 1, 2003 at 6:05 PM 5 replies 350+ views
Original Post
jamessharpe
jamessharpe
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.
civguy
civguy
The leak is elsewhere. Or Node/Leaf allocate memory they never release. Or they don''t have proper copy constructors/assignment operators.
jamessharpe
jamessharpe
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.

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



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


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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.