While executing below code, i found it is not functional due to segmentation fault error,even though
memry allocation has been done propery in below code but still not sure why this error is coming.
i will appreciat e if somebody help me as just month before i started learning c++.

#include<iostream.h>

#include<conio.h>

#include<string.h>

using namespace std;



class Derived1

{

char *s;

int m_length;

public:

Derived1(const char*);

Derived1( const Derived1& obj);

void show()const  {cout<<"str="<<s;}



~Derived1(){



delete [] s;}

};



Derived1::Derived1(  const char *str="")

{   



         m_length=strlen(str)+1;//null terminator

         cout<<m_length;

         s=new char[m_length];

         strncpy(s,str,m_length);

         s[m_length-1]='\0';//as loop start from 0





 }



Derived1::Derived1( const Derived1 &obj)

       {

        if(obj.m_length)

        {

        cout<<obj.m_length;      

        s=new char [m_length];//crash

        strncpy(s,obj.s,m_length);

        s[m_length-1]='\0';

        } 



        else

        {

         s= new char[1];

         s='\0'; //no need to perform deep copy  Derived s1 case



        }           



       }



int main()

{

  Derived1 s1; 

  Derived1 s2("mohan");

  s2.show();

  Derived1 s3=s2;

cout<<"s2.show";

s3.show();

getch();



}

Try putting a getter for your m_length variable, used to set the m_length field in the copy constructor:

const int getMlen() const{return m_length;}

and

Derived1::Derived1( const Derived1 &obj){
    if(obj.getMlen()){
        m_length = obj.getMlen();
        cout<<obj.m_length;
        s=new char [m_length];//crash
        strncpy(s,obj.s,m_length);
        s[m_length-1]='\0';
    }
    else{
        s= new char[1];
        s='\0'; //no need to perform deep copy  Derived s1 case
    }
}

You have not overloaded the = operator. You need to do that as well when working with pointers. you should implement it like your copy constructor. What compiler/IDE are you using? I ask because the headers you have are not correct. Also have you thought about using the string class instead of char arrays?

Hi Nathan ,

In above case i am initializing one object from other object of same type so only copy constructror will be called . I can't use string here as in my original assignment we do use raw pointers only so that i can easily sync up with legacy c API.
I am using Dev-c++ 4.9.9.2 compiler.

Thanks Andrew, It works. but still i am wondering in case if we don't construct
s1 object and try to run the programme( without implementing getMlen()) it works fine.
Could you explain.

 int main()

 {

 Derived1 s1;

 Derived1 s2("mohan");

 s2.show();

 Derived1 s3=s2;

 cout<<"s2.show";

 s3.show();

 getch();



 }

I read this article

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.