Search code examples
boostboost-test

Boost.Test doesn't treat memory leaks as failure


#define BOOST_TEST_MODULE test
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(test)
{
    int * i = new int;
    BOOST_CHECK(i==0);
}

Above test case obviously fails. The memory leak is also reported properely. However, if I change the test from i==0 to i!=0, it succeeds without problems and doesn't care that there is a memory leak.

Is this a bug or did I miss some configuration to make Boost.Test treat memory leaks as failures ?

EDIT

Boost.Test can be easily expanded to fail a test if memory is leaked. For future readers I include my solution:

#define MY_TEST_CASE(name)              \
    void my_test_cases__##name();       \
    BOOST_AUTO_TEST_CASE(name)          \
    {                                   \
        mytests::heap heap_scope;       \
        my_test_cases__##name();        \
        (void)heap_scope;               \
    }                                   \
    void my_test_cases__##name()

namespace mytests
{
    class heap
    {
#   if !defined(NDEBUG) && defined(_MSC_VER)
    public:
        heap()
        {
            _CrtMemCheckpoint(&oldState);
        }

        ~heap()
        {
            _CrtMemState curState, diffState;

            _CrtMemCheckpoint(&curState);

            int leaked_memory = _CrtMemDifference(&diffState,&oldState,&curState);

            BOOST_REQUIRE(leaked_memory==0);
        }

    private:
        _CrtMemState oldState;
#   endif
    };
}

Then just use MY_TEST_CASE instead of BOOST_AUTO_TEST_CASE

MY_TEST_CASE(test)
{
    // various
    // tests
    // .
    // .
    // .
}

And your unit tests will report an error and fail if any heap memory leaked.


Solution

  • Boost Test is a Unit Test framework.

    Leak detection is not a core feature.

    The documentation says:

    Memory leaks detection

    The Execution Monitor provides a limited ability to detect memory leaks during program execution, and to break program execution on specific memory allocation order-number (1 - first allocation of memory in program, 2 - second and so on).

    Unfortunately this feature is, at the moment, implemented only for the Microsoft family of compilers (and Intel, if it employs Microsoft C Runtime Library).

    Also it can not be tuned per instance of the monitor and is only triggered globally and reported after the whole program execution is done. In a future this ought to be improved.