CppUTest has memory leak detection support on a per-test level. This means that it automatically checks whether the memory at the end of a test is the same as at the beginning of the test.
Explained another way:
The memory leak detector consists of three parts:
All of these are on by default. For the macro support, you'll need to add to your Makefile:
CXXFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorNewMacros.h CFLAGS += -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h
These are added by default when you use the CppUTest Makefile helpers.
If you want to disable the memory leak detection (because you got too much memory leaks?) then you can do so by passing CPPUTEST_USE_MEM_LEAK_DETECTION=N to the makefile when you compile CppUTest.
It is common for the memory leak detection macros to conflict with an overloaded operator new or with STL. This is because the macro replaces the call to operator new to a call to operator new with __FILE__, and __LINE__. If you overload operator new, it will replace your overloaded definition resulting in a compiler error. This is common when using Standard C++ library (STL).
The easiest way is not to pass the --include MemoryLeakDetectionNewMacros.h to the compiler, but this would lose all your file and line information. So this is not recommended. An alternative is to create your own NewMacros.h file which will include the STL file *before* the new macro is defined. For example, the following NewMacros file can be used for a program that uses std::list:
#include "list" #include "CppUTest/MemoryLeakDetectorNewMacros.h"
Now the call to the compiler needs to be -include MyOwnNewMacros.h and this will ensure that the operator new overload is *before* the define and thus all compiler errors are resolved.
This one is harder (and luckily less common). You can solve this the same way as the conflict in STL, but its probably better to use a finer grained control. So, instead you can temporary disable the new macros, overload operator new, enable the new macro again. This can be done with the following code:
class NewDummyClass
{
public:
#if CPPUTEST_USE_NEW_MACROS
#undef new
#endif
void* operator new (size_t size, int additional)
#if CPPUTEST_USE_NEW_MACROS
#include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
{
// Do your thing!
}
};
Yes, its ugly. But usually people don't overload operator new everywhere. If you do, consider turning off the new macro completely.