【发布时间】:2020-12-23 06:42:17
【问题描述】:
我以为下面的代码 sn-ps 会导致双重释放,程序会核心转储。但事实是我运行代码时没有错误?
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;
}
如下修改代码sn-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;
}
那么还有一个问题,为什么这个程序每次都会转储内核?
【问题讨论】:
-
为什么没有错误显示有双重释放? - 因为不需要编译器为类似的事情提供诊断。首先不要使用拥有指针。
标签: c++ memory-management memory-leaks free