Car*_*bon 3 c++ memory-leaks crt
我有下面的代码,我认为基于Find Memory Leaks Using the CRT Library,应该打印出内存泄漏的行号。
#include "stdafx.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
void derp()
{
int* q = new int;
}
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
derp();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到以下信息:
Detected memory leaks!
Dumping objects ->
{75} normal block at 0x0067E930, 4 bytes long.
Data: < > CD CD CD CD
Object dump complete.
Run Code Online (Sandbox Code Playgroud)
根据 Microsoft 的文档,我希望看到分配泄漏内存的行的打印输出,但我没有。
我做错了什么?我正在使用 VS2015。
从MSDN 主题:
这些技术适用于使用标准 CRT malloc 函数分配的内存。但是,如果您的程序使用 C++ new 运算符分配内存,则您可能只会在内存泄漏报告中看到全局运算符 new 的实现调用 _malloc_dbg 的文件和行号。由于该行为不是很有用,您可以更改它以使用如下所示的宏报告进行分配的行:
#ifdef _DEBUG
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
// Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the
// allocations to be of _CLIENT_BLOCK type
#else
#define DBG_NEW new
#endif
Run Code Online (Sandbox Code Playgroud)
然后new用DBG_NEW. 我测试了它,它可以与您的代码正常工作。
其实,更换new与DBG_NEW无处不在的代码过于繁琐的任务,所以可能你可以使用这个宏:
#ifdef _DEBUG
#define new new( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#else
#define new new
#endif
Run Code Online (Sandbox Code Playgroud)
我测试了这个方法,它也有效。
| 归档时间: |
|
| 查看次数: |
2122 次 |
| 最近记录: |