我想在 DEBUG 模式下检查内存泄漏。我使用 Windows,为了完成这项工作,函数 _CrtDumpMemoryLeaks .
现在,为什么这段代码会发现内存泄漏?
#include <Windows.h>
#include <iostream>
int main()
{
if(_CrtDumpMemoryLeaks() == TRUE)
std::cerr << "MEMORY LEAK!" << std::endl;
return 0;
}
编辑:
我添加此代码以将输出定向到控制台:
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
输出是:
最佳答案
你有没有包括<crtdbg.h>
?
你确定你在 Debug模式下运行吗?
在非 Debug模式下 - 调用 _CrtDumpMemoryLeaks()
被预处理器删除,只留下 if(TRUE)
编辑: 此外,为了检测内存泄漏,您需要添加以下行以使用 malloc 和 free 的调试版本 - 请参阅 here .您可以尝试添加这些吗?
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
关于c++ - 为什么 _CrtDumpMemoryLeaks 在这里报告内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11292930/