Using CppUnit for memory leak detection

c++, cppunit, memory-leaks, unit-testing

Solution

If you're running on Linux, you could run your tests with memcheck.

The Client Requests section of the manual describes several useful macros, of which one is noted as being useful for testing:

`VALGRIND_COUNT_LEAKS`: fills in the four arguments with the number of bytes of memory found by the previous leak check to be leaked, dubious, reachable and suppressed. Again, useful in test harness code, after calling `VALGRIND_DO_LEAK_CHECK`.

The macro is defined in `memcheck.h` (likely in `/usr/include/valgrind`), and the sequence you want will resemble

unsigned long base_definite, base_dubious, base_reachable, base_suppressed;
VALGRIND_DO_LEAK_CHECK;
VALGRIND_COUNT_LEAKS(base_definite, base_dubious, base_reachable, base_suppressed);
// maybe assert that they're zero!

// call test

unsigned long leaked, dubious, reachable, suppressed;
VALGRIND_DO_LEAK_CHECK;
VALGRIND_COUNT_LEAKS(leaked, dubious, reachable, suppressed);
CPPUNIT_ASSERT_EQUAL(base_leaked, leaked);
// etc.

Repeating that for every test would be a pain, so you might write macros of your own or, even better, a specialized TestRunner.

Problem

Is anyone aware of extensions to CppUnit that can be used to make assertions on a test by test basis concerning memory leaks. i.e. CPPUNIT_ASSERT_NO_LEAKS()? Essentially, I want to be able to fail specific tests when the execution of the test results in leaked memory.

Original source