0x7C29F7A9(ucrtbased.dll?在(Project3.exe)处抛出异常:0xC0000005:写入位置0x00740000时访问冲突

Kai*_*ang -1 c++

我正在学习 C++,我在 Visual Studio 中运行了这些代码,但是我遇到了访问冲突异常,VS 告诉我异常发生在第 24 行,在 func中的strcat()mystring& operator+(mystring& z)。你能帮我找出原因吗?

#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;
 }
Run Code Online (Sandbox Code Playgroud)

Mik*_*ine 5

在第 47 行:

t1 = i + s3;

您正在连接i到作为基础的缓冲区s3。然而,作为基础的缓冲区s3i它本身。因此,您将一个字符串连接到其自身上。这不会有好的结局。

正如https://en.cppreference.com/w/c/string/byte/strcat注释:

如果字符串重叠,则行为未定义。

(请注意,如果您正在创建一个常规字符串类,您应该拥有该类中的缓冲区,就像 reqularstd::string一样。事实上,std::string除非您这样做是为了练习,否则您应该使用它)