Wednesday, October 27, 2010

Memory leak detection using _CrtSetAllocHook

Tip - We can use _CrtSetAllocHook function to monitor all the memory allocation and deallocation in an application. Please note that it will work only in debug mode.

Details - _CrtSetAllocHook allows an application to hook its own allocation function into the C run-time debug library memory allocation process. As a result, every call to a debug allocation function to allocate, reallocate, or free a memory block triggers a call to the application's hook function. _CrtSetAllocHook provides an application with an easy method for testing how the application handles insufficient memory situations, the ability to examine allocation patterns, and the opportunity to log allocation information for later analysis. When _DEBUG is not defined, calls to _CrtSetAllocHook are removed during preprocessing.

The _CrtSetAllocHook function installs the new client-defined allocation function specified in allocHook and returns the previously defined hook function. The following example demonstrates how a client-defined allocation hook should be prototyped:

int YourAllocHook( int allocType, void *userData, size_t size, int
blockType, long requestNumber, const unsigned char *filename, int

The allocType argument specifies the type of allocation operation (_HOOK_ALLOC, _HOOK_REALLOC, and _HOOK_FREE) that triggered the call to the allocation's hook function. When the triggering allocation type is _HOOK_FREE, userData is a pointer to the user data section of the memory block about to be freed. However, when the triggering allocation type is _HOOK_ALLOC or _HOOK_REALLOC, userData is NULL because the memory block has not been allocated yet.
size specifies the size of the memory block in bytes, blockType indicates the type of the memory block, requestNumber is the object allocation order number of the memory block, and, if available, filename and lineNumber specify the source file name and line number where the triggering allocation operation was initiated.

References - 

A very good code which can be reused for memory detection in the applications is available at

Posted By : Xavier K Joseph

No comments:

Post a Comment