STL Vector Memory Tricks
I’ve been playing around with stl vectors and their allocation /deallocation of memory. I’ve created a dummy program to illustrate a problem i’ve seen and its solution.
If you erase all the elements in a vector, the vector does erase them but doesn’t deallocate the memory from itself. Remember that at any point a vector has a certain amount of memory allocated to it, you can increase that memory by the reserve and resize methods (and obviously by adding to the vector) but how do you shrink the vector?
Well you really cant, unless you create another vector with size you want and swap it with the first one? Unfortuneatly this just creates another vector and uses up even more memory.
This generally wont be problem unless you have some massive global vectors that used alot of memory and you need to definately free up. The solution is quiet simple…
vector<type>().swap(myVector);
Just swap the vector with an empty temporary variable that goes out of scope immediately. Quick and simple.
The source code below basically has a test program that creates a vector of double arrays and fills it up then empties it and finally deallocates the memory. It clearly shows the amount of memory allocated to the vector by the system during runtime.
Vector Example Program: vectorMemLeak.cpp