删除导致的分段错误(核心转储)
Segmentation fault (core dumped) caused by delete
删除为对象分配的一些内存时遇到错误。你能帮我分析为什么会发生这种情况吗?该错误是由"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 创建的对象
您的问题是因为您试图删除程序无法触及的内容,从某种意义上说,地址不在您的范围内。
之所以如此,是因为您给出了一些要删除的随机地址。 删除栏 ,其中在堆栈中分配的内存的柱线假定在堆中,这是不正确的,因此您会出现崩溃。
相关文章:
- 如何找出GDB的SIGTRAP核心转储的根本原因
- C++映射分割错误(核心转储)
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 浮点异常(核心转储)#694457
- 分段错误(核心转储)但无法弄清楚
- 链接到libkcapi时没有核心转储
- 分段错误(核心转储) - 使用 SavedModel 的 Tensorflow C++ API 进行推断
- 在基数排序中,我得到 munmap_chunk():无效指针和中止(核心转储).为什么?
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- 合并排序:分段错误核心转储
- C++:分段错误(核心转储)
- 从 pybind11 构建导入模块时出现"分段错误(核心转储)"
- 如何使用 lldb 在曼扎罗中调试 lz4 文件格式的核心转储?
- qt C++命令行代码中的分段错误(核心转储)
- 从文件中读取的数据,但发生核心转储错误
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- C++ atof - 分段错误(核心转储)
- Linux C 只禁止我的程序使用核心转储
- 为什么我的代码包含错误分段错误(核心转储)?