Gold mine of Visual C++ tricks!
How to hook memory allocations?
![]()
Memory allocation hooking is always handy. For instance, if you want to know whether the memory leak is due to the 3ed party dll calls, then hook the memory allocation and then call the 3ed party api. If the dll does some memory allocation, then your hook function will be triggered. So far so nice – But how to hook the memory allocations?
![]()
You can use the function – AfxSetAllocHook(). See the code snippet below.
// The hook function.
BOOL AFXAPI AllocHook( size_t nSize,
BOOL bObject,
LONG lRequestNumber )
{
// bObject will be TRUE if the allocation
// is a CObject derived class.
return TRUE;
}
void SetHook()
{
// Set the hook.
AfxSetAllocHook( AllocHook );
// Try some allocations.
CDialog* pString = new CDialog;
int* integer = new int;
}
The bObject flag will be true if the allocation is for a CObject derived class.
![]()
AfxSetAllocHook() is only available in debug version. So take care!
![]()
Targeted Audience – Intermediate.
| Print article | This entry was posted by Jijo Raj on June 16, 2008 at 6:18 pm, and is filed under Codeproject, MFC. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |