vendredi 13 décembre 2019

What difference it's making when statically allocated memory for pointer vs dynamically allocated memory for pointer deletion? [duplicate]

#include<iostream>
using namespace std;
class A
{
   int x;
   int *ptr;
   int *ptr2;
   public:
   A(int y)
   {
     cout<<"para const"<<endl;
     x=y;
     ptr=&x;           //Static allocation
     ptr2=new int;     //Dynamic allocation
     (*ptr2)=y;
     cout<<"ptr "<<&ptr<<"--"<<ptr<<"--"<<*ptr<<endl;
     cout<<"ptr2 "<<&ptr2<<"--"<<ptr2<<"--"<<*ptr2<<endl;
   }
   void show()
   {
     cout<<x<<"--"<<(*ptr)<<"--"<<(*ptr2)<<endl;
   }
   ~A()
   {
     cout<<"dest"<<endl;
     //delete ptr;    //will leads to segmentation fault
     delete ptr2;
   }
};
int main()
{
   A obj1(10);
   obj1.show();
   A obj2(20);
   obj2.show();
   cout<<&obj1<<endl;
   cout<<&obj2<<endl;
}

OutPut:

para const
ptr 0x7ffe27dedbc8--0x7ffe27dedbc0--10
ptr2 0x7ffe27dedbd0--0x2132010--10
10--10--10
para const
ptr 0x7ffe27dedba8--0x7ffe27dedba0--20
ptr2 0x7ffe27dedbb0--0x2132030--20
20--20--20
0x7ffe27dedbc0
0x7ffe27dedba0
dest
dest

I can see for both the object, the pointers (1. statically allocated stored in stack and 2. dynamically allocated stored in heap) are created in separate memory & holding also separate memory . Then why deletion of ptr leads to segmentation fault and not for ptr2. I believe swallow copy & deep copy is not making any impact here as I am not copying the objects to one another. And also one more thing I am observing is the address of obj1 & obj2 is same as address of ptr & ptr2 , why so ?

Can someone explain me this behavior please ?

Aucun commentaire:

Enregistrer un commentaire