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();
}