Deleting a heap then dereferencing a pointer to that memory

前端 未结 4 917
误落风尘
误落风尘 2020-12-04 00:06

This is code from an exercise:

#include 
using namespace std;

int main() {
    int n = 13;
    int* ip = new int(n + 3);
    int* ip2 = ip;
         


        
4条回答
  •  遥遥无期
    2020-12-04 00:29

    Dereferencing the ip pointer will return what happens to be at that memory location at that time.

    It's returning 0 because that's what the four bytes at ip happen to encode to when cast as an integer.

    dereferencing a pointer after it's been deleted is unpredictable. It might be zero, it might be something else if that memory has been reallocated elsewhere.

    You're just lucky that it's 0 when you run your program.

提交回复
热议问题