views:

247

answers:

4

Im using a STL vector in my SDL program. and it looks like this: vector< Bullet * > vec; this makes a vector that can contain pointers to Bullet objects. when i run my program i only add one item at a time using: vec.push_back( new_bullet ); (new_bullet is a pointer to a "new" Bullet object. then in a following function i erase an object using: vec.erase(...); vec.size() shows that the items are being pushed and popped properly. I'm running Ubuntu 9.10 and System Monitor shows my programs memory usage slowly increasing. Is it my program or something I'm missing about STL vector?

+10  A: 

Sounds like you're not deleteing the "bullet" objects as you remove them from the vector.

Terry Mahaffey
+1 -- this sounds like the right answer.
Billy ONeal
A: 

If you're only adding to the end of the array and you're worried about memory fragmentation, you might want to use std::list instead. The only problem is, list accesses are O(n) time if they're not at the beginning.

Are you calling free()/delete on your bullets when you're done with them after pulling them out of the vector?

Platinum Azure
`std::list<t>::end()` is an O(1) operation because the list remembers both sides of the accessed element. Only elements in the middle of the list require O(n) time.
Billy ONeal
Also, the question was not about memory fragmentation, it was about increasing memory usage.
Billy ONeal
+3  A: 

erase() only removes an element from a vector, it does not delete the memory pointed to if that element is a pointer. This makes sense... imagine you had a vector<const char *> of string literals and did v.erase(i); you can't delete a const char *!

However, erase() will call the destructor for the element removed. So if you used a sort of "pointer object" rather than a pointer, it could release the memory when destroyed. If you're interested, you should check out boost::shared_ptr which implements reference counted garbage collection.

ccmonkey
"pointer object" is usually referred to as a *smart pointer*.
GMan
You can delete const pointers, by the way.
Steve Jessop
A: 

While I'm guessing the original poster is not freeing his "popped" pointers (pop doesn't do that for you), std::vector has another "feature" that may cloud it issue. std::vector overallocate space such that every push_back doesn't entail a reallocation and copy of the existing contents. In other words, the space used for vector is generally more than what's returned by .size().

Take a look at the shrink-to-fit idiom if you wish to make a std::vector take up no more space than it needs to hold its elements. Not useful if you are constantly manipulating the vector, but once you have everything loaded, it can save some space.

Jesse K