Heap corruption when using delete [] p;

Using delete [] p will damage the heap.

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 changed delete [] to

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

This works, but why can't I use delete [] p? Delete [] p only deletes p [0] and what does [] mean in delete [] p?

+4
source share
3 answers

delete [] x is for dynamically allocated arrays, not arrays of pointers to dynamically allocated elements, which 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. 
+6
source

delete [] used only after highlighting with new [] and delete only after new .

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

 Rectangle *p = new Rectangle[3]; ... delete [] p; 
+9
source

p is an array of pointers, and when you delete only [] p, you delete only the array of pointers, not the objects that they point to. Therefore, for this you need to iterate over the entire array to remove the object created in each pointer. The same thing happens when using two-dimensional dynamic arrays.

-1
source

Source: https://habr.com/ru/post/1487310/


All Articles