什么有用的东西可以用Visual C ++调试CRT分配钩子,除了找到可重现的内存泄漏? [英] What useful things can I do with Visual C++ Debug CRT allocation hooks except finding reproduceable memory leaks?

查看:186
本文介绍了什么有用的东西可以用Visual C ++调试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(每个程序运行都是相同的)终止,所以我写了以下内容:

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函数)并将调用堆栈存储在数据结构

  • 在解除分配挂钩中,删除该分配的调用堆栈信息

  • 在应用程序结束时,循环数据结构并报告所有调用堆栈。这些是分配内存但未被释放的地方。

  • Make a data structure where you map the allocated pointer to additional information
  • In the allocation hook you could query the current call stack (StackWalk function) and store the call stack in the data structure
  • In the de-allocation hook, remove the call stack information for that allocation
  • At the end of your application, loop over the data structure and report all call stacks. These are the places where memory was allocated but not freed.

这篇关于什么有用的东西可以用Visual C ++调试CRT分配钩子,除了找到可重现的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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