Search code examples
c++memory-leaksdefault-constructor

how many memory leak we have here?


i couldn't find my answer with googling so im asking here : Assume that we have code like this and we don't want to overload the copy constructor

 #ifndef ARRAY_H
 #define ARRAY_H

 class Array { 
      public:
      Array(int = 10);

      int* ptr; 
      int size;
               }
 #endif // ARRAY_H

and we have:

#include <iostream>
#include "Array.h"
using namespace std;

Array::Array(int A)
 {
    size = (A > 0) ? A : 10;
    ptr = new int[size];

    for(int i=0; i<size; i++)
     { ptr[i] = i;}
 }

and main() is :

   Array newArray1(10); 
   Array newArray2(8);
   newArray2 = newArray1;

now our professor said we have dangle problem here because we have same address for both newArray1 and newArray2
my question is if we delete newArray1 memory : have we memory leak except dangle??? what happened to newArray2's ptr's memory which ptr was pointing to it before getting newArray1 address??? is this part of memory exist now ??? and have we other memory leaks problem ???


Solution

  • To answer your question: You have no destructor delete[]ing the memory you allocate to ptr in the constructor. So yes, you have a leak.

    A much better option would be to simply use a std::unique_ptr rather than manual memory management.

    Also, why are you not using the constructors initialization list but instead assigning to members in the constructor body?