C++ deleting a pointer when there are 2 pointers pointing to the same memory locations

后端 未结 4 1948
既然无缘
既然无缘 2020-12-17 07:26

Lets say, I have one pointer

int *l1 = new int[100*100];

int *l2 = l1;

Now, l1 & l2 both point to the same sequ

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 08:11

    i2 still points to the same place, but that memory has now been freed. Trying to access anything through it is undefined behaviour, which means your values may be printed, or your house may catch on fire. It's not up to you.

    To be pedantic, neither i1 nor i2 are deleted, but the memory they pointed to is. They still retain their same values, but the memory there can now be reused for other things. It's unsafe to use a pointer that has been passed to delete because the memory might already have something else there.

提交回复
热议问题