Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

debugging - What useful things can I do with Visual C++ Debug CRT allocation hooks except finding reproduceable memory leaks?

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.

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;
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could also use it to find unreproducible memory leaks:

  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...