- CppUTest has a platform specific memory leak detection mechanism.
- If a test fails and has allocated memory prior to the fail and
that memory is not cleaned up by TearDown, a memory leak is reported.
It is best to only chase memory leaks when other errors have
been eliminated.
- Some code uses lazy initialization and appears to leak when it
really does not (for example: gcc stringstream used to in an
earlier release). One cause is that some standard library calls
allocate something and do not free it until after main (or never).
To find out if a memory leak is due to lazy initialization set
the -r switch to run tests twice. The signature of this situation
is that the first run shows leaks and the second run shows no
leaks. When both runs show leaks, you have a leak to find.
How is memory leak detection implemented?
- Before SetUp() a memory usage checkpoint is recorded
- After TearDown() another checkpoint is taken and compared to the
original checkpoint
- In Visual Studio the MS debug heap capabilities are used
- For GCC a simple new/delete count is used in overridden operators new,
new[], delete and delete[]
If you use some leaky code that you can't or won't fix you can tell a
TEST to ignore a certain number of leaks as in this example:
TEST(MemoryLeakWarningTest, Ignore1)
{
EXPECT_N_LEAKS(1);
char* arrayToLeak1 = new char[100];
}