为什么这段代码挂在提到的地方?

发布于 2024-12-04 07:36:16 字数 1074 浏览 1 评论 0原文

这是我为了研究 C++ 运算符重载而编写的一个简单示例。当我执行它时,代码挂在语句 c = a + b; 处并且控制永远不会到达 c.display();

作为调试的一部分,如果我将 cout <<指针 << '\n'; 在赋值运算符重载函数中,它确实打印出 HelloWorld,因此字符串似乎没有格式错误。

那为什么会挂呢?我缺少什么?

class mystring
{
    char *ptr;

    public:

   mystring(char *str = "")
   {
      ptr = new char[strlen(str) + 1];
      strcpy(ptr,str);

   } 

   mystring operator +(mystring s)
   {
      char *str = new char[strlen(ptr) + strlen(s.ptr) + 1];//where should this memory be freed
      strcpy(str,ptr);
      strcat(str,s.ptr);
      return mystring(str);
   }

   void operator =(mystring s)
   {
       strcpy(ptr,s.ptr);

      //cout << ptr << '\n'; \\Debug - this prints out HelloWorld but still hangs 
   }

   void display()
   {
       cout << ptr << '\n';
   }

   ~mystring()
   {
      delete [] ptr; 
   }
};

int main()
{
   mystring a="Hello",b="World",c;

  c = a + b;

  c.display();

  getchar();

}

编辑:编译器:MS-Visual C++ 2010 Express / Windows。

This is a naive example I have coded to study C++ operator overloading. When I execute it, code hangs at the statement c = a + b; and control never reaches c.display();

As part of debugging if I put a cout << ptr << '\n'; in the assignment operator overloaded function it does print out HelloWorld, so string doesn't seem to be malformed.

Why does it hang then? What am I missing ??

class mystring
{
    char *ptr;

    public:

   mystring(char *str = "")
   {
      ptr = new char[strlen(str) + 1];
      strcpy(ptr,str);

   } 

   mystring operator +(mystring s)
   {
      char *str = new char[strlen(ptr) + strlen(s.ptr) + 1];//where should this memory be freed
      strcpy(str,ptr);
      strcat(str,s.ptr);
      return mystring(str);
   }

   void operator =(mystring s)
   {
       strcpy(ptr,s.ptr);

      //cout << ptr << '\n'; \\Debug - this prints out HelloWorld but still hangs 
   }

   void display()
   {
       cout << ptr << '\n';
   }

   ~mystring()
   {
      delete [] ptr; 
   }
};

int main()
{
   mystring a="Hello",b="World",c;

  c = a + b;

  c.display();

  getchar();

}

EDIT: Compiler: MS-Visual C++ 2010 Express / Windows.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

瞳孔里扚悲伤 2024-12-11 07:36:16

我认为您得到的是内存错误。此行:

c = a + b;

执行以下操作:

c.constructor()
c.operator=(a.operator+(b));

并且您的运算符=无法分配内存

void operator =(mystring s)
{
  // ptr is allocated enough memory for "", i.e. one byte
  strcpy(ptr,s.ptr); // copying more than one byte into one byte array
  //cout << ptr << '\n'; // this works, but you've trashed memory with the strcpy
} // stack might be corrupted here, depends where this is, so execution can end up anywhere

您需要的是:

void operator = (mystring &s) // reference!
{
  delete [] ptr;
  ptr = new char [strlen (s.ptr + 1)];
  strcpy (ptr, s.ptr);
}

I think that what you are getting is a memory error. This line:

c = a + b;

does the following:

c.constructor()
c.operator=(a.operator+(b));

and your operator= fails to allocate memory

void operator =(mystring s)
{
  // ptr is allocated enough memory for "", i.e. one byte
  strcpy(ptr,s.ptr); // copying more than one byte into one byte array
  //cout << ptr << '\n'; // this works, but you've trashed memory with the strcpy
} // stack might be corrupted here, depends where this is, so execution can end up anywhere

What you need is:

void operator = (mystring &s) // reference!
{
  delete [] ptr;
  ptr = new char [strlen (s.ptr + 1)];
  strcpy (ptr, s.ptr);
}
烦人精 2024-12-11 07:36:16

你的 operator= 坏了。在执行 strcpy 之前,您没有正确分配足够的(或任何)内存。这会导致未定义的行为。

your operator= is broken. You aren't properly allocating enough (or any) memory before doing the strcpy. This leads to undefined behavior.

有木有妳兜一样 2024-12-11 07:36:16

<块引用>

char *str = new char[strlen(ptr) + strlen(s.ptr) + 1];//应该在哪里释放这块内存

在析构函数上释放内存。

在操作符 = 上,您必须释放分配的内存并再次分配它

char *str = new char[strlen(ptr) + strlen(s.ptr) + 1];//where should this memory be freed

Memory freed on destructor.

On operator = you must free the allocated memory and allocate it again

眼波传意 2024-12-11 07:36:16

运算符 = 应该释放旧缓冲区,然后像在构造函数中一样分配一个新缓冲区。

operator = should free the old buffer and then allocate a new one like you do in the constructor.

じ违心 2024-12-11 07:36:16

该代码似乎没有任何明显的问题会导致它在调用 c.display() 之前阻塞,但它可能看起来就像是这样做的。

操作cout <<指针 << '\n'; 不会刷新流,这意味着输出可能会被缓存到稍后的时间。整个程序可能已经基本上完成,正在等待用户在getchar()中输入字符。

尝试在调试器中运行代码或将输出更改为 cout <<指针 <<结束;

顺便说一句:您在 operator+ 中泄漏了内存,应该解决它。我知道您已经询问过如何做到这一点,您可能不喜欢(或理解)所提出的解决方案,但保持原样并不是解决方案。

operator= 不能确保您有足够的空间来保存完整的字符串,这意味着您可能会触发未定义的行为。

The code does not seem to have any obvious issue that would make it block before hitting c.display(), but it might look like it is doing so.

The operation cout << ptr << '\n'; does not flush the stream, and that means that the output might be cached until a later time. It might be the case that the whole program has basically completed and is waiting for the user to enter a character in getchar().

Try running the code in a debugger or changing the output to cout << ptr << endl;.

BTW: You are leaking memory in operator+, and should probably take care of it. I know you already asked about the way to do it, you might not have liked (or understood) the solutions that were proposed, but leaving it as it is is no solution.

operator= is not ensuring that you have enough space to hold the complete string, which means that you could be triggering Undefined Behavior.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文