1
class Text
{
public :   
       char& operator[](int pos) const   
       {return text[pos];}

        char* get() const
       {return text;}
private: 
     char* text = "hello";
};
int main() 
{
     Text a;
    char * x = &a[0];
    *x = 's';
    
    cout << a.get() << endl;

}

I was following Scott Meyers Effective C++ book, there was a class that I had to implement myself, so I tried implementing it my self, but this program keeps crashing.

X caliber
  • 52
  • 4

1 Answers1

2

This line:

char* text = "hello";

is not valid C++, since string literals decay to a const char *. With the correct command line flags, your compiler should have warned you about this.

Following on from there, *x = 's'; results in undefined behaviour, because x is pointing into said string literal. In practise, you get a seg fault, since you are trying to write to read-only memory.


Edit: Here's a fixed version using std::string:

#include <string>

class Text
{
public :   
     char& operator[](int pos) {return text[pos];}
     const char* get() const {return text.c_str ();}
private: 
     std::string text = "hello";
};

int main() 
{
    Text a;
    char * x = &a[0];
    *x = 's';
    
    std::cout << a.get() << std::endl;
}

Live demo

Paul Sanders
  • 24,133
  • 4
  • 26
  • 48