tylkonachwile
tylkonachwile

Reputation: 2267

How to delete dynamic allocated array in c++?

I got stuck with deleting an dynamically allocated array of int. I've got a destructor, where I'm trying to use a loop for to delete all elements of array and finally delete it. I have code on http://rextester.com/OTPPRQ8349 Thanks!

class MyClass
{
   public:
   int _a;
   int* c;
   int fRozmiar;
   static int fIlosc;
   MyClass() //default constructor
   {
       _a=0;
       c = new int [9];
       for(int i = 0; i<=9; i++)
       {
           c[i] = 1;
       }
       fIlosc++;
   }
   MyClass(int a1, int c1) // parametrized constructor
   {
       _a=a1;
       c = new int [c1];
       for(int i = 0; i<=c1; i++)
       {
           c[i] = rand();
       }
       fIlosc++;
   }
   MyClass(const MyClass &p2) // copy constructor
   {
    _a =p2._a;
    c = p2.c;
    fRozmiar = p2.fRozmiar;
    fIlosc = fIlosc;
    fIlosc++;
   }
    ~MyClass(); // destructor

    static int getCount() {
         return fIlosc;
      }
};

//Initialize static member of class
int MyClass::fIlosc = 0;
MyClass::~MyClass()
{
        for(int i = 0; i<sizeof(c); ++i)
        {
            delete[] c[i];
        }
        delete[] c;
       fIlosc--;
}
int main()
{
}

Upvotes: 0

Views: 1582

Answers (2)

Pete Becker
Pete Becker

Reputation: 76305

There are several problems in the code.

First, that loop in the destructor must go. If you didn’t new it, don’t delete it.

Second, a loop through an array of N elements should be for (int i = 0; i < N; ++i). Note that the test is i < N, not i <= N. The loops as currently written go off the end of the array. That’s not good.

Third, the copy constructor copies the pointer. When the first object goes out of scope its destructor deletes the array; when the copy goes out of scope its destructor also deletes the array. Again, not good. The copy constructor has to make a copy of the array. In order to do that the class needs to also store the number of elements the array.

Upvotes: 3

fgb
fgb

Reputation: 18569

Remove the for-loop, but keep the delete[] c after it.

Each int doesn't need to be deleted because they're not dynamically allocated. If you needed to delete them, then the for-loop wouldn't work becuase: sizeof(c) is not the size of the array, and delete[] should have been delete instead.

Upvotes: 4

Related Questions