Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a heap then dereferencing a pointer to that memory

This is code from an exercise:

#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;
}

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.

Why is this?

like image 438
bugmenot77 Avatar asked May 29 '09 20:05

bugmenot77


1 Answers

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

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.

like image 66
mmx Avatar answered Oct 04 '22 22:10

mmx