Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yet another C++ vector memory leak question

I'm attempting to make an algorithm that can draw the entities of my isometric game in the correct order. My entities are stored in a vector of pointers.

In the drawing function I first create a new vector of the same pointers, and then start with a for-loop that loops the amount of entities that I want to have drawn. Inside that loop there is yet another loop, which determines what entity to be drawn, and when an entity is drawn it's pointer is removed from the vector using vector.erase(), so the same entity wont be drawn twice (Which is why I'm creating a copy of the vector that is containing the entity pointers).

Anyway, my code itself works, and the entities are drawn the way I want, but I appear to have a memory leak (I can actually see the memory in the Windows Task Manager climb by 28 kb/s).

The memory leak remains even if I outcomment everything except this:

vector<Entity*> list = ent_list; // ent_list is the list of entity pointers
list.clear();

So I guess I'm missing something, but I'm not sure what. I figured since I didn't use "new" the memory would be taken care of, but obviously it isn't... Hope someone can help me!

/feodor

like image 421
feodor Avatar asked Jan 27 '26 13:01

feodor


2 Answers

Reference for vector::clear says: "if the elements of the vector are pointers to objects, this function will not call the corresponding destructors". Are you sure you're not relying on this?

like image 178
tsiki Avatar answered Jan 30 '26 05:01

tsiki


No, standard containers only erase the memory they have created; std::list.clear(); will only invalidates and remove the iterators themselves, not the memory you have allocated.

you have to call std::list.remove() or std::list.erase() each iterator after another, and manually delete the pointers you had allocated yourself.

like image 36
Stephane Rolland Avatar answered Jan 30 '26 04:01

Stephane Rolland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!