1

Now we have to create class X (as base class) and class Y (as derived). They both uses integer pointers to hold different size of allocations.

class X
{
  int *p;
  public:
         X() {p=new int[2];}
         ~X() {delete[] p;}
};

class Y : public X {
  int *q;
  public:
         Y() {q=new int[4];}
         ~Y() {delete[] q;}
};

And let's try it in a simple loop:

for(int i=0;i<8;i++){X *ptr =new Y; delete ptr;}

What causes the memory leak there and what can we do to fix it?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

1

Every execution for this loop

for(int i=0;i<8;i++){X *ptr =new Y; delete ptr;}

your program first creates an integer pointer with size 2 (2*4=8 bytes allocated) and latter creates an integer pointer with size 4 (4*4=16 bytes allocated) but just deletes the first one. So for every loop, it leaks 16 bytes just because of you cannot reach the deconstructor in derived class Y.

It's called Memory leak caused by lack of virtual deconstructor in base class. When you make the deconstructor in class X virtual, then compiler will be able to delete Y-type pointers. So you have to change this statement

~X() {delete[] p;}

into this:

virtual ~X() {delete[] p;}