How to iterate all MFC objects allocated on heap?

4 08 2008

MFC is famous for memory leaks. Usually we add icing and cherrys to those leaks by adding our own leaks. Is there any mechanism to track those?

Well, if you’re object is a mfc object, which is derived from CObject, then MFC provides an iteration mechanism to iterate through your objects. You can use it to track the count of your objects in heap, you can dump selective objects… etc… etc… Well, how can you do it?

Use the api – AfxDoForAllObjects(). While calling we’ve to pass a function pointer of expected syntax, and for each CObject derived object in heap, the function will be called. See the sample to iterate all CDynLinkLibrary objects and to find its count.

// This function will be called as callback
// from AfxDoForAllObjects.
void DoForAllObjects(CObject* pObject, void* pContext)
    // Here context is the pointer to count variable.
    int* pCount = (int*) pContext;

    // Check whether the object is of type CDynLinkLibrary
    if( dynamic_cast<CDynLinkLibrary*>( pObject))
        // Increment count.


// Iterate objects.
void CDialogDlg::Iterate()
    // Iterate all CObject instances and get the
    // count of instances of CDynLinkLibrary objects.
    int DynLinkLibCount = 0;
    AfxDoForAllObjects( DoForAllObjects, &DynLinkLibCount );


You can utilize this for finding memory leaks, to find the count of instances of a particular class, you can dump objects of particular class, etc…

Well, one thing to remember – its only available in debug build. So take care! 😉

Targeted Audience – Intermediate.