title: How to check for memory leaks in a class in C++?
body: <p>I am aware of several other threads that have discussed a similar questions. Also I am aware that one must deallocate all the allocated resources and nothing should be left unaccounted for. The reason I am asking this question is to see if there is a way to automatically detect a memory leak in a class. In particular, I am trying to implement an automated way to detect the leak within the unittest so that future development of that class would be more robust. Since my class is using several other classes within and some DLL's as well, it is difficulat, if not impossible to keep track of the leaks in all of those, so such a unittest may help.</p>
  
  <p>I was thinking of a couple of solutions to be able to check for memory leaks within a class. Assuming my class is something similar to this:</p>
  
  <pre><code>class MyClass
  {
      MyClass() { /* Lots of allocations */ }
      ~MyClass() { /* Lots of deallocations */ }
  }
  </code></pre>
  
  <ol>
  <li><p>In the test function, instantiate the class instance many times
  and destruct everytime. Meanwhile, check the task manager (in
  Windows at least) to see if the allocated memory for your
  application ramps up or remains substantially flat:</p>
  
  <pre><code>TEST( MyClass, MyClass)
  {
      int some_big_number = 10000;
      for (int i=0; i&lt;some_big_number; i++)
      {
          MyClass *myC = new MyClass;
          delete myC;
      }
  }
  </code></pre></li>
  <li><p>Allocate some dummy variable before and after the instantiation and
  destruction of the class instance and check if the two addresses are
  the same. Something like this:</p>
  
  <pre><code>TEST( MyClass, MyClass)
  {
      int address_1 = 0, address_2 = 0;
  
      int *tmp_1 = new int;
      address_1 = tmp_1;
      delete tmp_1;
  
      MyClass *myC = new MyClass;
      delete myC;
  
      int *tmp_2 = new int;
      address_2 = tmp_2;
      delete tmp_2;
  
      EXPECT_TRUE( address_1 == address_2 );
  }
  </code></pre>
  
  <p>My assumption is that if there is no memory leak within MyClass and
  all the claimed memory has been properly deallocated, the addresses
  of tmp_1 and tmp_2 should be the same. I am just not sure if memory
  allocation works that way.</p></li>
  <li><p>Use a plugin or program such as <a href="http://www.deleaker.com/" rel="nofollow">deleaker</a> or <a href="http://valgrind.org/" rel="nofollow">Valgrind</a>, but
  that may make my code or test unfavorably large and I am not sure if
  that can be used in the context above    anyway.</p></li>
  </ol>
  
  <p>Thanks!</p>