I have just resolved a memory leak in my application and now I want to write a unit test to ensure that this does not happen again.
I\'m look for a way to detect th
I really like ValGrind for this sort of thing. These tools already exist; you don't need to write your own unit tests to detect memory leaks.
That is not a unit test. If you want to make sure some unit that is supposed to manage a resource does not leak that resource then you need to validate that the resource it is managing gets deleted at the correct times. You can do this with mock objects which increment a counter on construction and decrement on delete...then make sure the count is right.
A test that checks the memory usage of an entire application is not something for a unit test. Unit tests are for particular units within the application.
Boost.Test will automatically tell you at the end of a test run if any of your unit tests leaked memory.
I don't know if any of the other C++ unit testing frameworks provide this kind of functionality.
You can also use google test framework (gtest) and then use google performance tools (gperf) to find leaks. GPerf puts in a replacement memory library and if there is a memory leak found after the test run completes it will let you know and gives you a pprof command to run with several different output formats - text, dot, web, etc. This tool will find leaks in both tests and production code.
I also use Valgrind to confirm if there is a leak when questionable but prefer gperf
. One gotcha is that if you have compiled with the gperf
memory library and try to use Valgrind
, it won't find any issues because it catches the leaks so you need to clean compile between switching or have a second copy of the project.
For Linux or other systems that use GLibC there are functions to get memory allocation statistics. Assuming no lazy allocations, you should have the same memory committed to malloc before and after you perform your test.
ProcessExplorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) works well for that.