删除指针时程序崩溃
Program crashes when deleting a pointer
大家好 我的代码是:
class aClass
{
public:
int data;
aClass* pointer=NULL;
aClass(int x): data(x) {
cout << "calling int constructorn";
}
~aClass() {
delete pointer;
cout <<"Index " <<this->data<<" calling destructorn";
}
};
int main()
{
aClass ob1(1);
ob1.pointer=new aClass(2); // let's say the new object is called ob2
ob1.pointer->pointer=new aClass(3);// let's say the new object is called ob3
delete ob1.pointer; //destory ob2, which will destory ob3 in sequentially.
return 0;
}
我期望输出是这样的:
calling int constructor
calling int constructor
calling int constructor
Index 2 calling destructor
Index 3 calling destructor //I think when ob2is destoyed ob3 will be destoyed
//too, but this is not in the output even though I delete "delete pointer" in
//the destructor
Index 1 calling destructor
但是程序崩溃了,我知道它在析构函数中的"删除指针"使程序崩溃,但我不知道它为什么崩溃以及为什么 ob3 没有被解救?
当退出 main
时,ob1
会自动销毁,因此调用其析构函数。再次删除pointer
,从而导致崩溃。请勿手动删除ob1.pointer
。
这是一个基本示例,可帮助您了解正在发生的事情。
class C
{
public:
C* p;
C() : p(NULL)
{}
~C()
{ delete p; }
};
int main()
{
C a;
// ...
// Lets say a.p == 5 for some reason.
delete a.p;
// The memory at address 5 is now deleted, but a.p remains unchanged.
// a.p is still 5, but accessing it is now illegal.
return 0;
// Stack cleanup -> a is destroyed.
// a´s destructor is called, which attempts to delete its p.
// This p is a.p which was deleted earlier.
// Remember, a.p is still 5, and now it is deleted in ~C.
// -> You deleted the memory at address 5 twice.
}
相关文章:
- 提升 ASIO Async_receive崩溃程序
- 类指针方法崩溃程序
- get_body来自 IHTMLDocument2 崩溃程序
- 是否有可能存在不会崩溃程序的内存问题
- 调试运行时出现奇怪的崩溃程序(Eclipse C++)
- 儿童对话框 - setWindowTexta或sendmessagea崩溃程序-MFC
- 顶点阵列GLFW崩溃C 程序
- 将值分配给Float数据类型崩溃程序
- OpenCV-将变量添加到类成员崩溃程序
- boost::interprocess::managed_shared_memory 崩溃程序
- 将枚举值分配给整数崩溃程序
- SDL 1.2 -> SDL 2.0(崩溃程序)
- 空析构函数崩溃程序:C++
- 冒泡排序崩溃程序c++
- Ofstream关闭崩溃程序
- 删除字符* 崩溃程序
- c++矢量擦除崩溃程序
- Lua_getglobal崩溃程序
- 通过Copy Constructor创建的e2打印崩溃程序
- RNG崩溃c++程序