Allocation Hooks and C Run-Time Memory Allocations
Applies to: Visual Studio Visual Studio for Mac
Note
This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here
A very important restriction on allocation hook functions is that they must explicitly ignore _CRT_BLOCK
blocks. These blocks are the memory allocations made internally by C run-time library functions if they make any calls to C run-time library functions that allocate internal memory. You can ignore _CRT_BLOCK
blocks by including the following code at the beginning of your allocation hook function:
if ( nBlockUse == _CRT_BLOCK )
return( TRUE );
If your allocation hook doesn't ignore _CRT_BLOCK
blocks, then any C run-time library function called in your hook can trap the program in an endless loop. For example, printf
makes an internal allocation. If your hook code calls printf
, then the resulting allocation will cause your hook to be called again, which will call printf again, and so on, until the stack overflows. If you need to report _CRT_BLOCK
allocation operations, one way to circumvent this restriction is to use Windows API functions, rather than C run-time functions, for formatting and output. Because the Windows APIs don't use the C run-time library heap, they won't trap your allocation hook in an endless loop.
If you examine the run-time library source files, you will see that the default allocation hook function, CrtDefaultAllocHook (which simply returns TRUE), is located in a separate file of its own, DBGHOOK.C. If you want your allocation hook to be called even for the allocations made by the run-time startup code that is executed before your application's main function, you can replace this default function with one of your own, instead of using _CrtSetAllocHook.