除了查找可重现的内存泄漏之外,我可以使用 Visual C++ Debug CRT 分配挂钩做哪些有用的事情? [英] What useful things can I do with Visual C++ Debug CRT allocation hooks except finding reproduceable memory leaks?

查看:14
本文介绍了除了查找可重现的内存泄漏之外,我可以使用 Visual C++ Debug CRT 分配挂钩做哪些有用的事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Visual C++ 调试运行时库功能所谓的分配钩子.以这种方式工作:您定义一个回调并调用 _CrtSetAllocHook() 来设置该回调.现在,每次完成内存分配/释放/重新分配时,CRT 都会调用该回调并传递一些参数.

Visual C++ debug runtime library features so-called allocation hooks. Works this way: you define a callback and call _CrtSetAllocHook() to set that callback. Now every time a memory allocation/deallocation/reallocation is done CRT calls that callback and passes a handful of parameters.

我成功地使用分配钩子找到了一个可重现的内存泄漏 - 基本上 CRT 报告说有一个未释放的块程序终止时的分配号 N(每次程序运行时 N 都相同),所以我在钩子中写了以下内容:

I successfully used an allocation hook to find a reproduceable memory leak - basically CRT reported that there was an unfreed block with allocation number N (N was the same on every program run) at program termination and so I wrote the following in my hook:

int MyAllocHook( int allocType, void* userData, size_t size, int blockType, 
    long requestNumber, const unsigned char* filename, int lineNumber)
{
     if( requestNumber == TheNumberReported ) {
         Sleep( 0 );// a line to put breakpoint on
     }
     return TRUE;
}

因为每次我都可以在 if 语句中放置一个断点并等到它被击中然后检查调用堆栈时报告的泄漏具有完全相同的分配编号.

since the leak was reported with the very same allocation number every time I could just put a breakpoint inside the if-statement and wait until it was hit and then inspect the call stack.

我可以使用分配钩子做哪些其他有用的事情?

What other useful things can I do using allocation hooks?

推荐答案

您还可以使用它来查找不可重现的内存泄漏:

You could also use it to find unreproducible memory leaks:

  • 创建一个数据结构,将分配的指针映射到其他信息
  • 在分配挂钩中,您可以查询当前调用堆栈(StackWalk 函数)并将调用堆栈存储在数据结构中
  • 在取消分配挂钩中,删除该分配的调用堆栈信息
  • 在您的应用程序结束时,循环遍历数据结构并报告所有调用堆栈.这些是分配内存但未释放的位置.

这篇关于除了查找可重现的内存泄漏之外,我可以使用 Visual C++ Debug CRT 分配挂钩做哪些有用的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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