Saturday, April 10, 2010

How do you know where the memory leaks when you have multiple files?

One Way to detect the memory leaks is to check that while using Inheritance and Virtual Functions some where we have initialized baseclass pointer with the derived class object but when calling destructor the destructor that u have used in the baseclass is not declared as Virtual.
eg:
#include
using namespace std;

class Base1 {
public:
  ~Base1() { cout << "~Base1()\n"; }
};

class Derived1 : public Base1 {
public:
  ~Derived1() { cout << "~Derived1()\n"; }
};

class Base2 {
public:
  virtual ~Base2() { cout << "~Base2()\n"; }
};

class Derived2 : public Base2 {
public:
  ~Derived2() { cout << "~Derived2()\n"; }
};

int main() {
  Base1* bp = new Derived1; // Upcast
  delete bp;
  Base2* b2p = new Derived2; // Upcast
  delete b2p;
}

The output of the following program is :--
~Base1()
~Derived2()
~Base2()

In this example we can see that after declaring the destructor of class Base2 as virtual when we delete a pointer to class Base2 then first the Derived2() destructor is called first then the base class destructor. So during upcasting this can introduce a memory leak.This is the case that i know which can introduce memory leak in multiple files.(Reference: TICPP Vol1 Bruce Eckel Chapter 15(polymorphism and Virtual functions))

0 comments:

Post a Comment