Share via

How to fix memory leaks in C++

Stuart Ray 0 Reputation points
2026-05-30T09:03:56.64+00:00

Debugging my C++ program, on closing the Output window shows "Memory leak detected, Objects dumped"

How do I find the offending objects?

Developer technologies | Visual Studio | Debugging

1 answer

Sort by: Most helpful
  1. AI answer

    2026-05-30T09:04:17.99+00:00

    Use the debug heap tools to identify which allocations weren’t freed and where they were made.

    For MFC code:

    1. Take memory snapshots around the suspected code using CMemoryState:
         #ifdef _DEBUG
         CMemoryState oldMemState, newMemState, diffMemState;
         
         oldMemState.Checkpoint();
         {
             // Do your memory allocations and deallocations...
             CString s("This is a frame variable");
             CPerson* p = new CPerson("Smith", "Alan", "581-0215");
             // delete p;  // if missing, this leaks
         }
         newMemState.Checkpoint();
         
         if (diffMemState.Difference(oldMemState, newMemState))
         {
             TRACE("Memory leaked!\n");
             diffMemState.DumpAllObjectsSince();
         }
         #endif
      
    2. Run under the debugger and look at the Output window. DumpAllObjectsSince prints all blocks that weren’t freed.
    3. The number in braces {n} at the start of each line is the allocation sequence number. To break exactly when a leaked block is allocated, set _afxBreakAlloc to that number before running again:
         #ifdef _DEBUG
         _afxBreakAlloc = 123; // allocation number from the dump
         #endif
      
      When the program hits that allocation, the debugger breaks and the call stack shows where the leak originates.
    4. For CObject-derived classes, override Dump to get more useful information in the dump:
         class CPerson : public CObject
         {
         public:
         #ifdef _DEBUG
             virtual void Dump(CDumpContext& dc) const;
         #endif
             CString m_firstName;
             CString m_lastName;
         };
         
         #ifdef _DEBUG
         void CPerson::Dump(CDumpContext& dc) const
         {
             CObject::Dump(dc);
             dc << "last name: " << m_lastName << "\n"
                << "first name: " << m_firstName << "\n";
         }
         #endif
      
    5. Place Checkpoint calls outside the scope of local frame variables so their temporary heap allocations don’t clutter the leak report.

    For general CRT-based C/C++ code:

    1. Enable the CRT debug heap in debug builds:
         #define _CRTDBG_MAP_ALLOC
         #include <stdlib.h>
         #include <crtdbg.h>
      
    2. At startup, enable automatic leak checking:
         int main()
         {
             _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
             // ...
         }
      
      This causes _CrtDumpMemoryLeaks to run at process exit and print leaks to the Output window.
    3. To get file/line information for new allocations, wrap new in a debug macro:
         #ifdef _DEBUG
             #define DBG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
         #else
             #define DBG_NEW new
         #endif
         
         int* p = DBG_NEW int[10];
      
      The leak report then shows the source file and line where the leaked allocation occurred.
    4. Interpret the leak report:
      • With _CRTDBG_MAP_ALLOC, entries look like:
             c:\path\project\file.cpp(20) : {18}
             normal block at 0x00780E80, 64 bytes long.
        
      • Use the file and line to locate the offending allocation and ensure the corresponding delete/free is called.
    5. _CrtDumpMemoryLeaks() can also be called manually near program shutdown to dump leaks on demand. It returns nonzero if leaks are present.

    Once the offending allocations are identified (via allocation number, file/line, or object dump), add the appropriate delete/free or fix ownership logic so those objects are released before program exit.


    References:

    AI-generated content may be incorrect. Read our transparency notes for more information.

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.