_CrtCheckMemory使用示例 [英] _CrtCheckMemory usage example

查看:139
本文介绍了_CrtCheckMemory使用示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解如何使用 _CrtCheckMemory 来跟踪我正在开发的Windows应用程序中的堆损坏。我似乎无法让它返回 false 。这是我的测试代码:

I'm trying to understand how to use _CrtCheckMemory to track down heap corruption in a Windows application I'm working on. I can't seem to get it to return false. Here's my test code:

int* test = new int[1];
for(int i = 0; i < 100; i++){
    test[i] = 1;
}
assert( _CrtCheckMemory( ) );

在上面的代码中, _CrtCheckMemory()返回true。我正在调试模式下运行。我还需要做些什么来获得 _CrtCheckMemory 标记问题的简单示例?

In the code above, _CrtCheckMemory( ) returns true. I'm running in Debug mode. What else do I need to do in order to get a simple example of _CrtCheckMemory flagging a problem?

推荐答案

需要额外的步骤,您必须说服编译器用调试分配器替换默认的新的运算符。只有调试分配器才能创建检测到堆块不足或覆盖的no-mans land区域。这是有风险的,使用原始分配器编译的代码不会很好地与不是的代码混合。所以它强制你明确选择加入。

An extra step is required, you must convince the compiler to replace the default new operator with the debug allocator. Only the debug allocator creates the "no-mans land" areas that detect an under- or overwrite of the heap block. It is risky, code that's compiled with the original allocator will not mix well with code that wasn't. So it forces you to opt-in explicitly.

最好在预编译的头文件(stdafx.h默认情况下)完成,所以你可以确定所有代码使用调试分配器。像这样:

That's best done in the pre-compiled header file (stdafx.h by default) so you can be sure that all code uses the debug allocator. Like this:

#ifdef _DEBUG
#  define _CRTDBG_MAP_ALLOC
#  define _CRTDBG_MAP_ALLOC_NEW
#  include <crtdbg.h>
#  include <assert.h>
#endif

CRTDBG宏获取malloc()函数和新的

The CRTDBG macros get the malloc() functions and the new operators replaced.

请注意,您发布的代码将首先触发另一个诊断。在Windows Vista及更高版本上,Windows堆分配器将首先投诉,因为该代码破坏了Windows堆的完整性。通过索引直到(例如2),使覆盖有点微妙。

Do beware that your code as posted will trigger another diagnostic first. On Windows Vista and up, the Windows heap allocator is going to complain first because the code destroyed the Windows heap integrity. Make the overwrite a bit subtler by indexing only up to, say, 2.

这篇关于_CrtCheckMemory使用示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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