C++ - 是否可以在单元测试中实现内存泄漏测试?

标签 c++ visual-studio unit-testing memory-leaks

我正在尝试为我的代码实现单元测试,但我很难做到。

理想情况下,我想测试一些类,不仅是为了获得良好的功能,还要为了正确的内存分配/释放。我想知道这个检查是否可以使用单元测试框架来完成。我正在使用 Visual Assert顺便提一句。如果可能的话,我希望看到一些示例代码!

最佳答案

您可以直接在 dev studio 中使用调试功能来执行泄漏检查 - 只要您的单元测试使用调试 c 运行时运行。

一个简单的例子如下所示:

#include <crtdbg.h>
struct CrtCheckMemory
{
  _CrtMemState state1;
  _CrtMemState state2;
  _CrtMemState state3;
  CrtCheckMemory()
  {
    _CrtMemCheckpoint(&state1);
  }
  ~CrtCheckMemory()
  {
    _CrtMemCheckpoint(&state2);
    // using google test you can just do this.
    EXPECT_EQ(0,_CrtMemDifference( &state3, &state1, &state2));
    // else just do this to dump the leaked blocks to stdout.
    if( _CrtMemDifference( &state3, &state1, &state2) )
      _CrtMemDumpStatistics( &state3 );
  }
};

并在单元测试中使用它:

UNIT_TEST(blah)
{
  CrtCheckMemory check;

  // TODO: add the unit test here

}

一些单元测试框架会自行分配 - 例如,Google 会在单元测试失败时分配 block ,因此任何因任何其他原因失败的测试 block 也总是会出现误报“泄漏”。

关于C++ - 是否可以在单元测试中实现内存泄漏测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2980917/

相关文章:

c++ - 运算符重载 c++ >> istream

c++ - 适用于任何 pc 的 Visual Studio 2017 C++ Exe(链接 vcruntime140.dll)

c# - Resharper 的 "Type argument is redundant"和断言存在问题

C++:有效地将 Sha256 摘要获取到 OpenSSL Bignum 中?

c++ - 为什么for循环不退出c++?

c++ - std::rename() 文件在使用 char 变量作为参数时不起作用(字符串转换为 char)

visual-studio - Visual Studio 2015 : Type universe cannot resolve assembly: System. 运行时,版本 = 0.0.0.0

c# - 从命令行在解决方案中仅构建一个项目

ios - Xcode 5 单元测试看到错误的类

javascript - 如何模拟事件并将其传递给 Jasmine 测试中的方法?