Search code examples
c++constructordestructorallocation

Deallocating memory from stack and heap


How can I deallocate memory stored for an array of known size?

The code below prints 4 times "constructor called!" but only once "Destructor called!" does it mean that memory for the whole array has been deallocated?

class Box
{
   public:
      Box() { 
         cout << "Constructor called!" <<endl; 
      }
      ~Box() { 
         cout << "Destructor called!" <<endl; 
      }
};

int main( )
{
   Box myBoxArray[4];

   delete myBoxArray; // Delete array

   return 0;
}

However if I declare myBoxArray dynamically, as shown in code below, the destructor is called 4 times.

class Box
{
    public:
      Box() { 
         cout << "Constructor called!" <<endl; 
      }
      ~Box() { 
         cout << "Destructor called!" <<endl; 
      }
}; 

int main( )
{
   Box* myBoxArray = new Box[4];

   delete [] myBoxArray; // Delete array

   return 0;
}

Is there a point of deallocating non-dynamically allocated memory or better leave it to garbage collector?


Solution

  • It is not the question of having point. You simply can't deallocate memory which you didn't allocate.

    delete [] myBoxArray; // Delete array
    

    has Undefined Behavior (UB), where anything or nothing can happen.

    You can only delete something which you did new, and you can only delete[] something which you did new[]. Any violations to this rule will make the program to misbehave.