0

I am trying to demonstrate concept of dangling pointer and so writing a program on it.

Suppose if u have pointer as a class variable and u don't write ur own copy constructor then it can lead to concept of dangling pointer.

Implicit copy constructor does a member wise copy of elements(shallow copy).So if one object goes out of scope it leads to problem of dangling pointer.

So is this program which i wrote to demonstrate dangling pointer correct? When i compiled it on ideone.com and it gave a runtime error.

#include"iostream"
using namespace std;
#include<string.h>

class cString
{
 int mlen;char* mbuff;   //**pointer** is a member of class

 public:
    cString(char *buff)  //copy buff in mbuff
    {
     mlen=strlen(buff);
     mbuff=new char[mlen+1];
     strcpy(mbuff,buff);
    }
    void display()       //display mbuff
    {
     cout<<mbuff;
    }

    ~cString()
    {
     cout<<"Destructor invoked";
     delete[] mbuff;               //free memory pointed by mbuff
    }
};

int main()
{
 cString s1("Hey");
  {
  cString s2(s1);            //call default copy constructor(shallow copy)
  s2.display();      
  }                   //destructor for object s2 is called here as s2 goes out of scope
 s1.display();               //object s1.display() should be unable to display hey

 return 0;
}
user3126632
  • 467
  • 2
  • 8
  • 15

0 Answers0