CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    Visual C++ General: How to I find the source of memory leaks?

    Q: When I run my program in debugger, I get a listing of memory leaks like this:
    Detected memory leaks!
    Dumping objects ->
    f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\strcore.cpp(141) : {381} normal block at 0x001FFC30, 54 bytes long.
    Data: < x > 0C 00 B9 78 12 00 00 00 12 00 00 00 01 00 00 00
    d:\marius\vc++\memoryleakstest\memoryleakstestdlg.cpp(163) : {380} normal block at 0x001FFBF0, 4 bytes long.
    Data: <@ > 40 FC 1F 00
    f:\dd\vctools\vc7libs\ship\atlmfc\src\mfc\thrdcore.cpp(306) : {374} client block at 0x001FFA38, subtype c0, 68 bytes long.
    a CWinThread object at $001FFA38, 68 bytes long
    Object dump complete.
    I can find the source of some of them, but not all. How do I find and fix them?

    A: You can use _crtBreakAlloc global variable to force the debugger break when the leaked block is allocated. To do this, you should follow several steps.

    1. Find a reproducible allocation number. Memory is allocated in blocks, and each block is identified by a number, called allocation number. When the debugger reports memory leaks, it includes the allocation number for the leaked block in brackets, like {381}.
    2. Put a breakpoint somewhere at the start of your program. This could be in the main function, in the constructor of your CWinApp derived class, or in InitInstance function, depending on the type of application you have and how early in the execution of the program the leaked block is allocated (lower numbers indicate early allocations).
    3. Run your program in debugger.
    4. When the program stops, open the Watch window, and add the following in the Name column: {,,msvcr90d.dll}_crtBreakAlloc. For the value, type the allocation number. Note: depending on the version of Visual Studio, you have to use the appropriate C runtime library file. msvcr90d.dll is from Visual Studio 2008.
    5. Continue debugging.
    6. Execution stops when the leaked block is allocated. The break will show this lines in dbgheap.c:
      Code:
      /* break into debugger at specific memory allocation */
      if (_crtBreakAlloc != -1L && lRequest == _crtBreakAlloc)
          _CrtDbgBreak();
      To figure where the allocation started in your code, open the Call Stack window and look down until you find the first call from your own code.
    Last edited by cilu; July 12th, 2010 at 03:16 AM.
    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured