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.
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:
class MyClass
{
MyClass() { /* Lots of allocations */ }
~MyClass() { /* Lots of deallocations */ }
}
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:
TEST( MyClass, MyClass) { int some_big_number = 10000; for (int i=0; i<some_big_number; i++) { MyClass *myC = new MyClass; delete myC; } }
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:
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 ); }
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.
Use a plugin or program such as deleaker or Valgrind, 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.
Thanks!