blue piranha
blue piranha

Reputation: 3874

Detected Memory Leak

I am trying to debug a very old, big C++ project. It is giving the following error:

 Detected memory leaks!
 Dumping objects ->
 {629} normal block at 0x0000000000084CA0, 16 bytes long.
 Data: <   ?            > D0 A7 F0 3F 01 00 00 00 00 00 00 00 00 00 00 00 
 {628} normal block at 0x0000000000084C20, 16 bytes long.
 Data: <   ?            > 10 A9 F0 3F 01 00 00 00 00 00 00 00 00 00 00 00
 {5667963} normal block at 0x000000000709FB20, 88 bytes long.
 ....
 ....
 Data: <p       3       > 70 D0 0F 07 00 00 00 00 33 00 00 00 00 01 00 00 
 Object dump complete.
 The program '[4892] Classifier.exe' has exited with code 0 (0x0).

I am unable to paste the program since its quite big but it goes like this

 void main(int argc, char *argv[]) 
 {
     try 
     {

    _CrtDumpMemoryLeaks(); //memory leak detection
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);   
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);  
    ....
    ....
     }
     catch()
    {   ....
    }
 }

In debug mode, the program runs successfully. However, in the output I see the above error message. No where in the output I am able to find the line number which would give me info on where is the memory leak detected.

Is there anything extra I need to add to view the line number?

Thank you

Upvotes: 2

Views: 2639

Answers (2)

nikau6
nikau6

Reputation: 961

According to the microsoft documentation to get a better report that shows name of the file and the line number where the leaked memory is first allocated, you first must include _CRTDBG_MAP_ALLOC

#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>

And if the program uses new, and not malloc, for the allocations, you must define this macro :

#ifdef _DEBUG
    #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#else
    #define DBG_NEW new
#endif

Which in your case, debugging an old program, if it's got a fair amount of files, is not very useful. But there's a trick that can be done,

#define new new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )

But this trick has some drawbacks. If a class overrides new for example, or if the program uses placement new.

You can too redefined the operator new and delete. Here's a excellent article about how that can be done to detect leaks in an old program: link

EDIT : Someone here gives a another way of using the macro DBG_NEWto debug a existing program, link

Upvotes: 1

Tiger Hwang
Tiger Hwang

Reputation: 300

Add this line after _CrtSetDbgFlag

 _CrtSetBreakAlloc(629);

629 is what you see in the dump log, it usually means the 629 allocation of memory. Run debug again you will stop at that allocation, then you can check call stack to see what's that.

Upvotes: 5

Related Questions