c++ - 在 Visual Studio 单元测试中检查内存泄漏

标签 c++ visual-studio memory-leaks

我主要是一名 Linux 开发人员,但是,我继承了一个存在内存泄漏的 Windows dll。 我知道原因并相信我已经解决了它。 我想在单元测试中检查一下。 单元测试使用内置的cppunit 测试框架,与cppunit 无关。我通常在 Linux 上使用的框架。 即

#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

我想做的是测量代码块前后的内存使用情况,并检查它是否没有改变——这表明存在内存泄漏。或者类似地,检查分配器类型函数分配的内存量是否恰好是后续析构函数类型函数释放的内存量。

是否有合适的 API 可以用来可靠地获取当前内存使用情况?

我天真地尝试了以下方法:

size_t getMemoryUsage()
{
    PROCESS_MEMORY_COUNTERS pmc;
    auto processHandle = GetCurrentProcess();
    if (GetProcessMemoryInfo(processHandle, &pmc, sizeof(pmc)))
    {
        return pmc.WorkingSetSize;
    }
    else 
    {
        Assert::Fail(L"Unable to get memory usage for current process");
    }
    return 0;
}

这给了我当前进程的内存使用情况。不幸的是,这并不能准确反射(reflect)正在进行的分配和释放。我认为如果我释放内存,操作系统可能仍会保留它供应用程序稍后使用。工作集是操作系统分配给进程的,而不是它在内部实际使用的内存。

我尝试通过 What is private bytes, virtual bytes, working set? 将其更改为 PrivateUsage但这似乎并不总是在 malloc 之后改变。

是否有合适的 API 可以为我执行此操作? 也许一个库可以像您在 Linux 上使用 LD_PRELOAD 那样替代经过检测的 malloc? 参见 ld-preload-equivalent-for-windows-to-preload-shared-libraries

这里有几个类似的问题-例如memory leak unit test c++ .

此问题特定于在 visual studio 中使用 cppunit 对 DLL 进行单元测试的情况。

DLL 不公开可重写的分配器接口(interface)。我想我的 目前最好的选择可能是增加一个。 如果有更简单的方法,我宁愿避免进行大量更改。 确认这是唯一方法的答案将被接受。

最佳答案

我不觉得尝试使用 OS API 是可靠的,就像我做的一样 p = new char[1024]; delete[] p; 无法保证内存会返回给操作系统,而且在许多情况下也不会。例如假设最小的页面大小是 4KB,很明显,为小对象分配 4KB 会很浪费,所以分配器 在你的进程中 将把这个较大的 block 分开,因此操作系统看不到是否这样碎片是否被释放。

这也适用于其他操作系统/编译器。如果您不断重复相同的测试循环“它一直在使用更多内存”,您可以确定随时间推移的趋势,但随后您必须去搜索它,并且负载不太一致,很难判断几 KB 的差异是否是一个是否泄漏。


Visual Studio 有许多集成度更高的工具可以提供帮助。这些通常假定您正在使用 new/deletemalloc/free 或 IDE 可能知道的其他类似内容。如果不是,则可能需要稍微调整 DLL,以便 IDE 能够以最准确的方式知道发生了什么。

例如,如果您使用内部内存“池”,系统只能知道该池分配了内存,而不知道它的用途或是否已返回到该池。


要查找执行中的内存泄漏(比如运行测试用例),您可以使用 memory leak detection功能。

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    char *leak = new char[1024];
}
The thread 0x3280 has exited with code 0 (0x0).
Detected memory leaks!
Dumping objects ->
{94} normal block at 0x0000021EF2EA1FD0, 1024 bytes long.
 Data:  CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
Object dump complete.
The program '[0xF64] test.exe' has exited with code 0 (0x0).

You can then set a break point to stop on that allocation next time to find it. You will need the program to run exactly the same for this to work, but for a unit test on a piece of suspect code that is generally doable.

You can do this by pausing your program at the very start in VS, then in the watch window setting {,,ucrtbased.dll}_crtBreakAlloc to the desired allocation number, say 94. Running your program it will stop inside the allocation in question, letting you see the stack trace etc.

By default this goes to the debug output, which is not easy to catch from automation, but you can redirect it to say stderr, then check if there is any "Detected memory leaks!" in your test output (along with test case success/fail/etc.).

_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);

您还可以包括文件和行号(请参阅 Microsoft 文档),但不幸的是,这通常更加困难,因为宏可能会破坏例如新的放置,并且在您没有直接分配的情况下不起作用您正在编译的源代码(现有库等)。


一个非常有用的 IDE 工具是 Memory Usage在诊断工具窗口中。

举个例子:

#include <stdio.h>
int main()
{
    for (int i = 0; i < 1000; ++i)
    {
        char *more_leaks = new char[100];
        sprintf(more_leaks, "Leaking %d memory", i);
        if (i % 55) delete[] more_leaks;
    }
}

在 VS 中,转到“调试”->“Windows”->“诊断工具”。

将程序运行到某个断点,然后单击新窗口中的“内存使用”选项卡。选项卡左侧是“拍摄快照”按钮。然后运行你的程序到你认为泄漏的函数之后,并拍摄另一个快照。

然后您可以查看分配是否存在差异、它们是什么、它们保存的数据是什么,并大致探索您程序中的内存。

enter image description here

关于c++ - 在 Visual Studio 单元测试中检查内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59407416/

相关文章:

c++ - 警告 : null character ignored [-Wnull-character] in C++

C++11:std::move() 调用参数列表

c# - 使用 NUnit 进行测试时应该如何处理数据文件?

java - 这是我的代码还是 Firebase 代码导致了这次泄漏?

javascript - 如何通过 "setInterval"kick ass pass scope

C++:使用类型信息测试类继承

c++ - 数组变量返回意外值

visual-studio - Visual Studio 2017 - Option Strict 不会关闭

c# - 如何禁用 VS datagridview 中的第一个自动选择?

jQuery 插件中的 JavaScript 内存泄漏