为什么_CrtDumpMemoryLeaks在这里报告内存泄漏? [英] Why is _CrtDumpMemoryLeaks reporting a memory leak here?

查看:112
本文介绍了为什么_CrtDumpMemoryLeaks在这里报告内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在调试模式下检查内存泄漏.我使用Windows,并且要执行此工作,请使用功能 _CrtDumpMemoryLeaks .

I want to check for memory leak in DEBUG mode. I use Windows and, to do this work, the function _CrtDumpMemoryLeaks.

现在,为什么这段代码会发现内存泄漏?

Now, why this code finds a memory leak?

#include <Windows.h>
#include <iostream>

int main()
{
    if(_CrtDumpMemoryLeaks() == TRUE)
        std::cerr << "MEMORY LEAK!" << std::endl;

    return 0;
}

我添加以下代码以将输出定向到控制台:

I add this code to direct output to console:

_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>?

确定要在调试模式下运行吗?

Are you sure you are running in debug mode?

在非调试模式下-对_CrtDumpMemoryLeaks()的调用将被预处理器删除,仅留下if(TRUE)

In non-debug mode - the calls to _CrtDumpMemoryLeaks() are removed by the pre-processor leaving just if(TRUE)

另外,要检测内存泄漏,您需要添加以下行以使用malloc和free的调试版本-请参见

Also to detect memory leaks you need to add the below lines to use the debug versions of malloc and free - see here. Can you try adding these?

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

这篇关于为什么_CrtDumpMemoryLeaks在这里报告内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆