Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GoogleTest and Memory Leaks

I'm surprised that Google C++ Testing Framework does not explicitly support checking for memory leaks. There is, however, a workaround for Microsoft Visual C++, but what about Linux?

If memory management is crucial for me, is it better to use another C++ unit-testing framework?

like image 701
Andrew Avatar asked Mar 20 '15 20:03

Andrew


2 Answers

If memory management is crucial for me, is it better to use another C++ unit-testing framework?

i don't know about c++ unit-testing, but i used Dr. memory, it works on linux windows and mac if you have the symbols it even tells you in what line the memory leak happened! really usefull :D
more info http://drmemory.org/

like image 106
Jotac0 Avatar answered Oct 18 '22 22:10

Jotac0


Even if this thread is very old. I was searching for this lately.

I now came up with a simple solution (inspired by https://stackoverflow.com/a/19315100/8633816)

Just write the following header:

#include "gtest/gtest.h"
#include <crtdbg.h>

class MemoryLeakDetector {
public:
    MemoryLeakDetector() {
        _CrtMemCheckpoint(&memState_);
    }

    ~MemoryLeakDetector() {
        _CrtMemState stateNow, stateDiff;
        _CrtMemCheckpoint(&stateNow);
        int diffResult = _CrtMemDifference(&stateDiff, &memState_, &stateNow);
        if (diffResult)
            reportFailure(stateDiff.lSizes[1]);
    }
private:
    void reportFailure(unsigned int unfreedBytes) {
        FAIL() << "Memory leak of " << unfreedBytes << " byte(s) detected.";
    }
    _CrtMemState memState_;
};

Then just add a local MemoryLeakDetector to your Test:

TEST(TestCase, Test) {
    // Do memory leak detection for this test
    MemoryLeakDetector leakDetector;

    //Your test code
}

Example:

A test like:

TEST(MEMORY, FORCE_LEAK) {
    MemoryLeakDetector leakDetector;

    int* dummy = new int;
}

Produces the output:

enter image description here

I am sure there are better tools out there, but this is a very easy and simple solution.

like image 6
Muperman Avatar answered Oct 18 '22 22:10

Muperman