我认为下面的代码片段会导致双重释放,并且程序会核心转储。但事实是,当我运行代码时没有错误?
Similar problem显示,它导致了双重免费!
我的问题是,为什么没有错误地显示有一个双重释放?为什么没有核心转储?
#include <iostream>
using namespace std;
int main()
{
int *p = new int(5);
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
}当我运行这个程序时,程序的输出如下所示:

如下所示修改代码片段后,发生了核心转储:
#include <iostream>
using namespace std;
int main()
{
int *p = new int(5);
for (;;)
{
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
}
return 0;
}程序输出为:

所以还有另一个问题,为什么这个程序每次都会核心转储?
发布于 2020-09-04 09:22:50
为什么没有错误地显示有一个双空闲?为什么没有核心转储?
delete p;
cout << "The value that p points to: " << (*p) << endl;引用已删除指针的时刻是程序进入未定义行为的时刻,然后不能保证会出现错误或崩溃。
这并不完全相同,但记忆和酒店房间之间的类比是适用的,这很好地解释了未定义行为的含义。强烈推荐阅读:
Can a local variable's memory be accessed outside its scope?
https://stackoverflow.com/questions/63733594
复制相似问题