How will you detect if there is memory leak in your C++ program?

Showing Answers 1 - 18 of 18 Answers

Herojeet

  • Nov 8th, 2007
 

Run "Rational Purify", it will show you all the leaks

  Was this answer useful?  Yes

abrankov

  • Nov 26th, 2007
 

 

Well, "Rational Purify" is one way. If I was conducting the interview I would ask a contra question immediately asking how to do that if you do not have a port of the tool for the OS (Riviera, Symbian etc.) you are using.
In this case you will need to find a way to precisely measure how much memory you have before and after you run the program. If there is a difference than you have a memory leak. How you do that vary from system to system. You will need to dig yourself in the documents for the system.

 

  Was this answer useful?  Yes

mukesh5sin

  • Dec 20th, 2007
 

If you are using new and delete operator, you can overload both the operators and can count number off heap allocation and deallocation. You can also get the __FILE__ and __LINE__ to get to know the file name and line number. Now the new and delete of a memory location should be in pair and if its not there is a memroy leak. By using line and file utility you can reach upto the exact location.

  Was this answer useful?  Yes

If memory cannot be allocated dynamically, new throws bad_alloc, such message will be displayed at execution.
If so, then
Use cout statement in destructor to check if it was invoked (i.e. memory deallocated)

  Was this answer useful?  Yes

By overloading the new and delete operators, we can find the memory leaks as shown in following program ,

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int count =0;
void * operator new(size_t size)
{
        count++;
        cout<<"The size of memory allocated:"<<size<<"byes"<<"n";
        return malloc(size);
};
void operator delete(void * mem)
{
        count--;
        free(mem);
};
int _tmain(int argc, _TCHAR* argv[])
{
    //int length = sizeof("Santhosh");
    char* Name = (char*)operator new (sizeof("HelloWorld"));
    strcpy_s(Name,sizeof("HelloWorld"),"HelloWorld");
    operator delete(Name);
    cout<<"The number of memory leaks:"<<count;
    getchar();
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions