Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Corruption of heap when using delete []p;

Tags:

c++

visual-c++

With I use delete []p, the corruption of heap will occur.

Rectangle *p[3];

for (int i = 0; i<3; i++)
  p[i] = new Rectangle();

p[0]->set(3, 4); 
p[1]->set(10, 8); 
p[2]->set(5, 6); 

for(int i=0; i < 3; i++) 
    cout << "Area is " << p[i]->area() << endl; 

delete []p; 

After I change delete [] to

for (int i = 0; i<3; i++)
    delete p[i]; 

It works but why I cannot use delete []p? Is delete []p only deletes p[0] and what [] means in delete []p?

like image 720
zzz Avatar asked Dec 09 '22 14:12

zzz


2 Answers

delete [] is only to be used after an allocation with new [], and delete only after new.

This is how C++ works. If you want to simply allocate an array of 3 Rectangle's, use this:

Rectangle *p = new Rectangle[3];

...

delete [] p;
like image 59
orlp Avatar answered Dec 28 '22 14:12

orlp


delete [] x is for dynamically allocated arrays, not for arrays of pointers to dynamically allocated elements, which is what you have:

Rectangle* pA = new Rectalgle[3]; // dynamically allocated array
....
delete [] pA;  // OK

Rectangle* p[3]; // array of pointers. 
// Each pointer must be dealt with individually.
delete p[0]; // Might be OK, if p[0] points to dynamically allocated Rectangle.
like image 26
juanchopanza Avatar answered Dec 28 '22 13:12

juanchopanza