【问题标题】:What happens, when changing ptr which is pointing to allocated memory using operator new to some other memory?当使用 operator new 将指向已分配内存的 ptr 更改为其他内存时会发生什么?
【发布时间】:2013-12-16 15:50:59
【问题描述】:
#include <iostream>
using namespace std;
int main()
{
int a = 10;
try
{
    int *p = new int;
    cout<<"p is pointing to address:"<<p<<endl;
    cout<<"Value at *p:"<<*p<<endl;

    p = &a;
    cout<<"a address:"<<&a<<endl;
    cout<<"p is pointing to address:"<<p<<endl;
    cout<<"Value at *p:"<<*p<<endl;

    delete p;

    cout<<"a address:"<<&a<<endl;
    cout<<"a val:"<<a<<endl;        
}
catch(bad_alloc &e)
{
    cout<<e.what()<<endl;
}
    return 0;

}

在上面的例子中,p指向的地址变成了&a。通过调用delete,逻辑上p的所指对象(删除p指向的东西)因为p指向a的地址,现在a的地址应该被释放到堆中。

我很想知道, 1.new分配的内存会怎样?它会导致内存泄漏吗? 2. 即使这看起来很傻,(无论如何记录我的想法都没有坏处)编译器是否知道 p 指向的地址并删除 operator new 分配的确切地址?

【问题讨论】:

标签: c++ memory-management


【解决方案1】:

在您的示例中,当您执行 delete 时,您正试图删除 一个堆栈变量,它将给出未定义的行为。

p 指向的原始 int 丢失并泄露。这段内存会一直丢失,直到程序退出。

编译器不会密切关注您的内存或任何其他运行时 函数,它只是将你的程序(你的愿望)翻译成机器代码。

【讨论】:

    【解决方案2】:

    你知道这个:

    int *p = new int;
    

    将为堆上的整数分配内存,其地址将存储在p
    现在,当你这样说时:

    p = &a;
    

    该地址被a 的地址覆盖,即p 现在包含a 的地址,而在堆上分配的整数地址消失了

    该内存现在泄露了

    当你说:

    delete p;
    

    这是危险,因为p 指向堆栈上的一个变量。

    here is why 你不应该那样做。


    链接的功劳归于 chue x,供他发表评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 2015-09-14
      • 2018-10-08
      • 1970-01-01
      • 2014-12-20
      • 2015-05-01
      • 1970-01-01
      相关资源
      最近更新 更多