删除导致的分段错误(核心转储)

Segmentation fault (core dumped) caused by delete

本文关键字:核心 转储 错误 分段 删除      更新时间:2023-10-16

删除为对象分配的一些内存时遇到错误。你能帮我分析为什么会发生这种情况吗?该错误是由"delete foo"语句引起的。

// pointer to classes example
#include <iostream>
using namespace std;
class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};

int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj's area: " << obj.area() << 'n';
  cout << "*foo's area: " << foo->area() << 'n';
  cout << "*bar's area: " << bar->area() << 'n';
  cout << "baz[0]'s area:" << baz[0].area() << 'n';
  cout << "baz[1]'s area:" << baz[1].area() << 'n';       
  delete bar;
  delete[] baz;
  delete foo; // This is the statement caused the error!!
  return 0;
}

/************************输出***************************************/

sh-4.2# main                                               
obj's area: 12                                             
*foo's area: 12                                            
*bar's area: 30                                            
baz[0]'s area:10                                           
baz[1]'s area:18                                           
Segmentation fault (core dumped)                           
sh-4.2#                                                    

您应该只对使用 new 分配的内存使用 delete

obj具有自动存储持续时间 - 如果范围,它将在外出时被销毁。 您不需要手动删除它,实际上这样做是一个错误,如您所见。

仅删除通过 new 创建的对象

您的问题是因为您试图删除程序无法触及的内容,从某种意义上说,地址不在您的范围内。

之所以如此,是因为您给出了一些要删除的随机地址。 删除栏 ,其中在堆栈中分配的内存的柱线假定在堆中,这是不正确的,因此您会出现崩溃。