GoogleTest 和内存泄漏

And*_*rew 8 c++ tdd unit-testing memory-leaks googletest

我很惊讶 Google C++ 测试框架没有明确支持检查内存泄漏。但是,对于 Microsoft Visual C++ 有一种解决方法,但是 Linux 呢?

如果内存管理对我来说至关重要,那么使用另一个 C++ 单元测试框架会更好吗?

小智 7

如果内存管理对我来说至关重要,那么使用另一个 C++ 单元测试框架会更好吗?

我不知道 C++ 单元测试,但我使用了内存博士,它可以在 linux windows 和 mac 上运行,如果你有符号,它甚至会告诉你内存泄漏发生在哪一行!非常有用:D
更多信息 http://drmemory.org/


Mup*_*man 6

即使这条线已经很老了。我最近正在寻找这个。

我现在想出了一个简单的解决方案(受到/sf/answers/1352057031/的启发)

只需编写以下标题:

#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_;
};
Run Code Online (Sandbox Code Playgroud)

然后只需将本地 MemoryLeakDetector 添加到您的测试中:

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

    //Your test code
}
Run Code Online (Sandbox Code Playgroud)

例子:

像这样的测试:

TEST(MEMORY, FORCE_LEAK) {
    MemoryLeakDetector leakDetector;

    int* dummy = new int;
}
Run Code Online (Sandbox Code Playgroud)

产生输出:

在此输入图像描述

我确信有更好的工具,但这是一个非常简单的解决方案。

  • 我希望您的解决方案适用于 Linux,但它仅适用于 Windows,因为 _CrtMem* 是 Windows 本机 API (2认同)