-1

I'm studying C++, I ran these codes in Visual Studio, but I got an access violation exception, VS told me the exception happened at line:24, in strcat() in func mystring& operator+(mystring& z). Could you please help me find out the reason?

#include <iostream>
#include <string.h>
#pragma warning(disable:4996)
using namespace std;

class mystring
{
private:
  char* p;
  int i;
 public:
  mystring(char* ps)
  {
      p = ps;
      i = strlen(ps) + 1;
  }
  mystring& operator+(char* s)
  {
      strcat(p, s);
      return *this;
  }
  mystring& operator+(mystring& z)
  {
      strcat(p, z.p);
      return *this;
  }
  friend mystring& operator+(char* d, mystring& s)
  {
      strcat(s.p, d);
      return s;
  }
  void print()
  {
      cout << this->p;
  }
 };
 int main()
 {
  char t[300] = "def", i[100] = "abc";
  mystring t1(i);
  t1 = t1 + t;
  t1.print();
  mystring s2(i);
  t1 = t1 + s2;
  t1.print();
  mystring s3(i);
  t1 = i + s3;
  t1.print();
  return 0;
 }
Mgetz
  • 5,108
  • 2
  • 33
  • 51
Kaiyu Yang
  • 45
  • 4

1 Answers1

5

On line 47:

t1 = i + s3;

You are concatenating i onto the buffer that underlies s3. However, the buffer that underlies s3 is i itself. So you are concatenating a string onto itself. This wont end well.

As https://en.cppreference.com/w/c/string/byte/strcat notes:

The behavior is undefined if the strings overlap.

(Note that if you are creating a regular string class you should own the buffer in the class, as reqular std::string does. Infact you should use std::string unless you are doing this for an exercise)

Mike Vine
  • 9,468
  • 25
  • 44