删除堆,然后取消对指向该内存的指针的引用 [英] Deleting a heap then dereferencing a pointer to that memory

查看:73
本文介绍了删除堆,然后取消对指向该内存的指针的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是练习中的代码:

#include <iostream>
using namespace std;

int main() {
    int n = 13;
    int* ip = new int(n + 3);
    int* ip2 = ip;
    cout << *ip << endl;
    delete ip;
    cout << *ip2 << endl;
    cout << ip << tab << ip2 << endl;
}

当删除分配给堆上int的空间时,我认为取消引用指针会产生某种内存错误.而是返回0.

When the space allocated to the int on the heap is deleted, I thought that dereferencing the pointer would give some sort of memory error. Instead, it returns 0.

这是为什么?

推荐答案

取消引用无效的指针会导致每个规范的结果不确定.它不能保证会失败.

Dereferencing an invalid pointer leads to undefined results per spec. It's not guaranteed to fail.

通常(取决于CPU/OS/compiler/...),编译器根本不关心它.它只是给出该内存地址当前的内容.例如,在x86架构中,仅当地址位于未映射到您的进程的内存页面中(或您的进程无权访问该地址)时,您才看到错误,因此CPU会引发异常(保护错误)操作系统将正确处理(保护错误)(可能会使您的进程失败).有时会使用一种技巧来使访问地址0始终会导致访问冲突:操作系统将页表中地址空间第一页的读/写位设置为0,以便对该页的任何访问都将始终产生异常.

Usually (CPU/OS/compiler/... dependent), the compiler doesn't really care about it at all. It just gives what's currently at that memory address. For example, in x86 architecture, you just see an error only when the address is in a memory page that's not mapped to your process (or your process doesn't have permission to access that), thus an exception will be thrown by the CPU (protection fault) which the OS would handle appropriately (and probably, making your process fail). A trick is sometimes used to make accessing the address 0 always cause an access violation: The OS sets the read/write bits of the first page of the address space in the page table to 0 so that any access to that page will always generate an exception.

这篇关于删除堆,然后取消对指向该内存的指针的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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