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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With