Unit testing destructors

I asked the excellent Kevlin Henney about techniques to test the destruction of pointers in C++. He suggested that the basic idea is to overload the “new” and “delete” operators and count how many times each is called. A testing framework can then check that the number of calls to new and delete balances out.

Testing destructors should definitely be tested in unit tests, but it strikes me that simply ensuring that new is called as many times as delete might not be sufficient. For example this function:

void leaky_function () {
   new double;
   delete NULL;

This code shows an overloaded new and delete that keeps counts allocation/deallocation. Note that the register that keeps track of which pointers have been allocated/deallocated cannot be an stl container, as these call “new” and delete themselves causing a stack overflow.

About jakirkpatrick

I am a researcher in solar energy at the University of Oxford. I am interested in mathematics, programming and trying to understand why things work. I also like the great outdoors and riding my bike.
This entry was posted in Uncategorized. Bookmark the permalink.

3 Responses to Unit testing destructors

  1. Szaki says:

    I think your question was not the right one. You want to avoid memory leaks. A quick Google search https://www.google.fi/search?q=memory+leak+test+c%2B%2B yields several tools for this:
    Boost.Test http://www.boost.org/doc/libs/1_44_0/libs/test/doc/html/index.html
    Deleaker: http://deleaker.com/
    Visual Leak Detector: http://vld.codeplex.com/

    • Unit testing the destruction of objects is about more than avoiding memory leaks, it’s about documenting that the code you have written works correctly.
      On top of that, the beauty of having overloaded new/delete is that you can use them just in your test program, without affecting the original code (unlike Visual leak detector that introduces a new dependency in your code). Deleaker is not free so no go!

      The boost unit test framework is the sort of thing that would do. I would envisage the pattern for testing an object to be :

      n_allocated_pointers_before = mem_register::count_allocations
      new object;
      delete object;
      n_allocated_pointers_after = mem_register::count_allocations

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s