title: Memory leak on vector._Reallocate() in Visual C++ Memory Debugger
body: <p>I have two vectors of pointers:</p>
  
  <ol>
  <li>A vector containing pointers to all objects</li>
  <li>A temporary vector containing pointers to some of the objects in the above vector. Each frame, this vector is cleared and pointers are then added again.</li>
  </ol>
  
  <p>No objects are created or deleted during these frames.</p>
  
  <p>According to Visual Studio's memory profiler I get a memory leak, in vector._Reallocate() every time I add a pointer to this vector.</p>
  
  <p>Image: <a href="http://i.stack.imgur.com/f4Ky3.png" rel="nofollow">http://i.stack.imgur.com/f4Ky3.png</a></p>
  
  <p>My question is:
  Does vector.push_back() allocate something that is not deallocated later, or is Visual Studio's memory profiler just confused because I'm clearing a vector without destroying the elements? This only happens in Debug mode - not in Release.</p>
  
  <p>I understand that the _Reallocate(..)-method allocates space on the heap, but since I clear the vector this should not cause a leak, I suppose?</p>
  
  <p><em>Update:  using std::list instead of std:.vector solves the "problem" - though I don't know if it really is a problem or not</em></p>
  
  <p><strong>Update2: It DOES happen in Release mode as well. I was a little bit confused by the output, but I get the same problem there</strong></p>
  
  <p>**Update3: I have attached some code that can reproduce the problem. I could only reproduce the problem if I store the vectors in a multidimensional array, like in the original problem.</p>
  
  <pre><code>class MyClassContainer
  {
  public:
      std::vector&lt;MyClass*&gt; vec;
  };
  
  int main(int args, char **argv)
  {
      std::vector&lt;MyClass*&gt; orig;
      MyClassContainer copy[101][101];
      for(int i = 0; i &lt; 101; i++)
          orig.push_back(new MyClass());
      while (true)
      {
          int rnd = std::rand() * 100 / RAND_MAX; int rnd2 = std::rand() * 100 / RAND_MAX;
          for (int i = 0; i &lt; 101; i++)
              for (int j = 0; j &lt; 101; j++)
                  copy[i][j].vec.clear(); // this should clear all??
          copy[rnd2][rnd].vec.push_back(orig[rnd]);
      }
  
      return 0;
  }
  </code></pre>
  
  <p><strong>Update 4:</strong> <em>The memory debugger shows an increasing number of heap allocations as time goes. However, I noticed now that if I wait for a long time the number of new heap allocations per second decreases towards 0. So apparently it's not really a memory leak.
  It seems that when each vector in the array has been pushed to at least once nothing more gets allocated on the heap. I don't understand why though.</em></p>