关于调试:为什么运行此c ++脚本后会得到:双重释放或损坏(顶部)?

Why do I get: double free or corruption (top) after running this c++ script?

我有以下代码:

1
Class Chain

1
char* c;

作为唯一的公共场所

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
istream& operator>>(istream& i, Chain& s) {
  delete [] s.c;
  const int L = 256;
  char *t = new char[L];
  i.getline(t,L);
  s.c = t;
  return i;
}

ostream& operator<<(ostream& o, Chain s) {
  o << s.c;
  return o;
}

#include <iostream>
#include"Chain.h"
using namespace std;

int main(){

      Chain id;

      cin >> id;

      cout << id;
      cout << id;

在Xubuntu(最新版本)上的Eclipse IDE下运行代码后,出现以下错误:

Error in [...] double free or corruption (top): 0x00000000008fd290 ***

有什么事吗


1
ostream& operator<<(ostream& o, Chain s) {

这不是对s的引用,它正在构建一个完整的副本,其中可能包含一个析构函数,该析构函数会删除所使用的内存。 而且由于您两次调用它,因此它两次被删除。


您的类Chain很可能具有销毁c的析构函数。 所以在这一行:

1
delete [] s.c;

您要删除c,然后在删除Chain时,它会再次尝试销毁c,以发现它已被删除,并且您正在执行双重释放。