删除指向对象的C ++指针 [英] Deleting C++ pointers to an object

查看:147
本文介绍了删除指向对象的C ++指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为delete命令将释放我分配的内存.有人可以解释为什么删除后我似乎仍在使用内存吗?

I thought that the delete command would free up memory I allocated. Can someone explain why it seems I still have the memory in use after delete?

class Test
{
public:
    int time;
};

int main()
{
    Test *e;

    e = new Test;

    e->time = 1;
    cout << e->time << endl;

    delete e;

    e->time = 2;
    cout << e->time << endl;

    return(0);
}

我希望在e-> time = 2之后出现段故障;

I expected a seg-fault after e->time = 2;

谢谢!

推荐答案

删除"内存时,基本上是在将分配的内存返回到堆中.这仅表示用于组织堆内存的数据结构已更新,以指示该内存现在可供使用.它没有清除或类似的东西.您正在访问仍然存在但属于操作系统的内存.这是未定义的行为.

When you "delete" memory, you are basically returning the allocated memory back to the heap. This just means that the data structure used to organize heap memory is updated to indicate that the memory is now available to use. It is not cleared out or anything like that. You are accessing memory that still exists, but belongs to the operating system at this point. This is undefined behavior.

顺便说一句,当您尝试从没有读取权限的段中读取内存时,会发生段错误.在平面内存模型中,这可能意味着您试图读取内核空间中的内存.可能是因为您取消引用了错误的指针.

And by the way, a seg fault occurs when you try to read memory from a segment that you do not have read permissions for. In a flat memory model this probably means you tried to read memory in kernel space; probably because you dereferenced a bad pointer.

这篇关于删除指向对象的C ++指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆