0

I saw this piece of c++ code under the topic of dangling pointer on the internet and tried executing it. This might not be pleasant to look at but here goes...

int *x, *y, *z;
x = new int;
*x = 3;
y = x;
delete x;
x = NULL;
z = new int;
*z = 5;
*y = 2;

When I print *z, it always turns out to be equal to the value of *y(as specified in the last line of code), 2 in this case but how is this possible if I specifically did *z = 5 in the second last line itself.

Sunny
  • 51
  • 1
  • 7
  • Likely because `y` happens to be pointing to the same memory location. This is UB however, so `y` pointing to the same memory location as `z` is not guaranteed. – ChrisMM Nov 23 '19 at 14:57

1 Answers1

0

With Undefined Behaviour, everything is possible.

In your case, object to which y is pointing is destroyed (it's a dangling pointer), and dereferencing y using *y is UB (even worse when you try to assign something there).

It seems that after delete x, compiler decided to assign the memory block to z in the new call, which is perfectly reasonable (but not guaranteed - absolutely any other free memory block would be also valid).
Since y happens to point to the very same block of memory, it looks like you can manipulate z pointee object using y, but you cannot - you have no idea where y is really pointing.

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52