0
#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 ?

abhisek
  • 337
  • 1
  • 3
  • 11
  • I think it is because `ptr` is pointing to a member of class which is not dynamically allocated. Segmentation fault occurs (as per my knowledge) when program tries to access wrong segment of memory. So dynamically allocated data are on heap and you can de-allocate memory from heap. But, if it's in other segment, de-allocation may not be allowed. – kiner_shah Dec 14 '19 at 04:39
  • Re. "_I am observing is the address of obj1 & obj2 is same as address of ptr_", see [https://stackoverflow.com/questions/7845012/why-do-class-members-have-the-same-address-as-their-object](https://stackoverflow.com/questions/7845012/why-do-class-members-have-the-same-address-as-their-object) – TrebledJ Dec 14 '19 at 04:42

0 Answers0