mor*_*des 6 windows debugging heap visual-studio-debugging
我正在尝试了解如何使用_CrtCheckMemory
来跟踪我正在处理的Windows应用程序中的堆损坏.我似乎无法让它回来false
.这是我的测试代码:
int* test = new int[1];
for(int i = 0; i < 100; i++){
test[i] = 1;
}
assert( _CrtCheckMemory( ) );
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,_CrtCheckMemory( )
返回true.我正在调试模式下运行.为了得到一个_CrtCheckMemory
标记问题的简单示例,我还需要做些什么?
需要额外的步骤,您必须说服编译器用调试分配器替换默认的new运算符.只有调试分配器才会创建检测堆块覆盖不足或覆盖的"无法域"区域.这是有风险的,使用原始分配器编译的代码将不能很好地与不是的代码混合.因此它迫使您明确选择加入.
这最好在预编译的头文件(默认为stdafx.h)中完成,因此您可以确保所有代码都使用调试分配器.像这样:
#ifdef _DEBUG
# define _CRTDBG_MAP_ALLOC
# define _CRTDBG_MAP_ALLOC_NEW
# include <crtdbg.h>
# include <assert.h>
#endif
Run Code Online (Sandbox Code Playgroud)
CRTDBG宏获取malloc()函数并替换新的运算符.
请注意,您发布的代码将首先触发另一个诊断.在Windows Vista及更高版本中,Windows堆分配器将首先抱怨,因为代码破坏了Windows堆的完整性.通过仅索引,例如2,使覆盖更微妙.