Debanik Dawn
Debanik Dawn

Reputation: 799

Program crash on copy constructor

I have the following code I was testing:

 #include<bits/stdc++.h>
 using namespace std;
 class Stringtype{
     char* str;
     int length;
     public:
     Stringtype(){
         str='\0';
         length=0;
     }
     Stringtype(const Stringtype& s){
         cout<<"Constructor"<<endl;
         strcpy(this->str, s.str);
         this->length = s.length;
     }

     Stringtype(char* text){
         strcpy(this->str, text);
         this->length = strlen(str);
     }
     friend ostream& operator<<(ostream& stream, Stringtype s){
         stream<<"Value :"<<endl;
         for(int i=0;i<s.length;i++){
              cout<<(s.str)[i];
         }
         cout<<endl;
         stream<<"Length :"<<endl;
         stream<<s.length<<endl;
         return stream;
     }
    friend istream& operator>>(istream& stream, Stringtype& s){
         cout<<"Enter the string"<<endl<<endl;
         s.str = new char[30];
         cin>>s.str;
         s.length = strlen(s.str);
         return stream;
     }
 };

 int main(){
     Stringtype s1, s2;
     cin>>s1>>s2;
     cout<<s1<<s2;
     cout<<(s1>s2)<<endl;
     cout<<(s1<s2)<<endl;
     cout<<(s1==s2)<<endl;
     cout<<(s1+s2)<<endl;
     return 0;
 }

This code produces the following output (after the input is taken properly):

Constructor

and then crashes.

I can't seem to understand why...

Any help is greatly appreciated. Thank you.

Upvotes: 1

Views: 692

Answers (3)

Devvrat Tomar
Devvrat Tomar

Reputation: 63

Try initializing str="", instead str='\0';

Upvotes: 0

Ranjini Srinivas
Ranjini Srinivas

Reputation: 1

Please change the following friend ostream& operator<<(ostream& stream, Stringtype s) to friend ostream& operator<<(ostream& stream, Stringtype& s)

Take the reference for the string s

Upvotes: 0

nvoigt
nvoigt

Reputation: 77285

You never actually reserve memory for your internal memory representation of your string. You need to have a new somewhere. Otherwise you will write to memory you don't own, which is exactly what is happening here, right in the next line after the output you observe.


By the way: there should be no copy-construction here, your signature

friend ostream& operator<<(ostream& stream, Stringtype s){

should read:

friend ostream& operator<<(ostream& stream, const Stringtype& s){

Doesn't change the fact that you have errors in your memory handling though.

Upvotes: 4

Related Questions