Debugging Memory Leaks, part 3.5: Hacks with Hooks

Alan rightfully comments that setting a conditional breakpoint at _heap_alloc_dbg  significantly slows down the application.

If run time is an issue for you even in debug builds and re-compilation is not an issue, here’s an alternative trick: use an allocation hook that detects a given allocation size. Within the hook itself you can set a break and detect the stack yourself, or dump the stack via a tracepoint.  Somewhere early in the application you’d need to assign it with _CrtSetAllocHook.

The hook can be as simple as:

int MyAllocHook( int allocType, void *userData, size_t size, int  blockType, long requestNumber,
const unsigned char *filename, int lineNumber)
return 1;

And the assignment as simple as:

BOOL MyApp::InitInstance()


To dump the call stack to the output window using the debugger, set a tracepoint in a line that runs only when your requested size is detected:

(Alternatively, set a regular breakpoint, then right click it at the breakpoints window and select ‘when hit…’).

Then, type $CALLSTACK at the message line:

Allocation hooks are often used in much heavier debugging facilities – usually involving procedurally walking call stacks (more on that some day). This is quite an overkill for a hack such as this, and the debugger supplies convenient alternatives anyway.

This entry was posted in Debugging, VC++. Bookmark the permalink.

1 Response to Debugging Memory Leaks, part 3.5: Hacks with Hooks

  1. Alexander G says:

    Good one! By the way, Ofek, we learned together Infi 1 in Technion. Nice to meet you :)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s