views:

154

answers:

3

I'm trying to implement unit testing for my code and I'm having a hard time doing it.

Ideally I would like to test some classes not only for good functionality but also for proper memory allocation/deallocation. I wonder if this check can be done using a unit testing framework. I am using Visual Assert btw. I would love to see some sample code , if possible !

+1  A: 

You might be able to detect memory leak on tests by providing your own implementation of new, delete, malloc and free functions, by adding memory tracking informations on allocation.

Klaim
This is something I would like to avoid...
sevaxx
Well, you will have to provide an alternate implementation of the allocator that tracks allocations. That doesn't mean you have to write it yourself...
Ben Voigt
That's right. Look online for allocator libs. Nedalloc is one I know (Ogre use it). If you don't want to use something like that, then you can use an external tool instead... but that will not be usable in your unit tests. In visual studio there is a basic memory leak checker but it's only good to detect that there is one, not providing always informations about the memory leaks...
Klaim
+2  A: 

You can use Google's tcmalloc allocation library, which provides a heapchecker.

(Note that heapchecking may add noticeable overhead to your program's performance, so you probably only want to enable it on debug builds or unit tests.)

And you asked for example code, so here it is.

Stephen
+6  A: 

You can use the debug functionality right into dev studio to perform leak checking - as long as your unit tests' run using the debug c-runtime.

A simple example would look something like this:

#include <crtdbg.h>
struct CrtCheckMemory
{
  _CrtMemState state1;
  _CrtMemState state2;
  _crtMemState state3;
  CrtCheckMemory()
  {
    _CrtMemCheckpoint(&state1);
  }
  ~CrtCheckMemory()
  {
    _CrtMemCheckpoint(&state2);
    // using google test you can just do this.
    EXPECT_EQ(0,_CrtMemDifference( &state3, &state1, &state2));
    // else just do this to dump the leaked blocks to stdout.
    if( _CrtMemDifference( &state3, &state1, &state2) )
      _CrtMemDumpStatistics( &state3 );
  }
};

And to use it in a unit test:

UNIT_TEST(blah)
{
  CheckCrtMemory check;

  // TODO: add the unit test here

}

Some unit test frameworks make their own allocations - Googles for example allocates blocks when a unit test fails, so the any test block that has a fail for any other reason always also has a false positive "leak".

Chris Becke
This is a very "clean" solution. I tried it (in an admittedly simple case) and it worked as expected. +1
sevaxx
I will second that. This is a really clean solution. Just calling the _CrtDumpMemoryLeaks function doesn't work with google test because it erroneously reports some leaks in the framework, but this solution avoids the said problem. You do have to remember to create an instance of the class at the top of every test case though.
tathagata