Search code examples
c++memorystdvector

Is it normal that memory usage keeps growing when clearing and filling a std::vector repeatedly?


I have a std::vector of a class called OGLSHAPE.

each shape has a vector of SHAPECONTOUR struct which has a vector of float and a vector of vector of double. it also has a vector of an outline struct which has a vector of float in it.

Initially, my program starts up using 8.7 MB of ram. I noticed that when I started filling these these up, ex adding doubles and floats, the memory got fairly high quickly, then leveled off. When I clear the OGLSHAPE vector, still about 19MB is used. Then if I push about 150 more shapes, then clear those, I'm now using around 19.3MB of ram. I would have thought that logically, if the first time it went from 8.7 to 19, that the next time it would go up to around 30. I'm not sure what it is. I thought it was a memory leak but now I'm not sure. All I do is push numbers into std::vectors, nothing else. So I'd expect to get all my memory back. What could cause this?

Edit

It's memory fragmentation from allocating lots of small things, how can that be solved?


Solution

  • Calling std::vector<>::clear() does not necessarily free all allocated memory (it depends on the implementation of the std::vector<>). This is often done for the purpose of optimization to avoid unnessecary memory allocations.

    In order to really free the memory held by an instance just do:

    template <typename T>
    inline void really_free_all_memory(std::vector<T>& to_clear)
    {
        std::vector<T> v;
        v.swap(to_clear);
    }
    
    // ...
    std::vector<foo> objs;
    
    // ...
    // really free instance 'objs'
    really_free_all_memory(objs);
    

    which creates a new (empty) instance and swaps it with your vector instance you would like to clear.