I have found on this website that delete
is used for single object deletion and delete[]
for multiple objects. If we invoke delete
on an array of objects, it invokes destructor for first object and then there is segmentation fault. Can anyone explain how this leads to segmentation fault?
I have the following piece of code:
#include <iostream>
using namespace std;
class A{
public:
A() {
cout<<hex<<this<<endl;
}
~A() {
cout<<hex<<this<<endl;
}
};
int main()
{
cout<<"Contructors: \n";
A* arr = new A[10];
cout<<"\n\nDestructors: \n";
delete arr;
return 0;
}
and the output is:
Contructors:
0x2243c28
0x2243c29
0x2243c2a
0x2243c2b
0x2243c2c
0x2243c2d
0x2243c2e
0x2243c2f
0x2243c30
0x2243c31
Destructors:
0x2243c28
*** Error in `./a.out': munmap_chunk(): invalid pointer: 0x0000000002243c28 ***
Aborted (core dumped)
I have figured out that delete[]
deletes the array in decreasing order of the addresses but this is not the case with delete
. Can anyone please explain what is going at the compiler end and Why ONE destructor is being invoked and then a segmentation fault?
Its just that why not 2 or 3 or 4 destructors being invoked before segmentation fault. WHY ONLY ONE?