I'm a bit confused about the output of the following code:
1 2 3 4 5 6 7 8
char* a = newchar;
char* b = a;
*b = 'Z';
cout << *b << *a << endl;
delete(a);
a = newchar;
*a = 'Y';
cout << *b;
As far as I know, up to the fourth line there is one memory address being pointed by both a and b, so changing *b will also affect *a. So far, so good. But then the memory address is being deleted (or marked as free) by delete(a). So both a and b now become invalid pointers and dereferencing them would cause undefined behavior.
But then pointer a receives a new memory address and it's storing a new character ('Y'). Pointer b hasn't been modified so it should still be invalid. Why is it then that cout << *b outputs 'Y'?
> Why is it then that cout << *b outputs 'Y'?
Because the system likes to mess with your head every so often ;)
Given something like this, it is quite likely that you're going to get back the same pointer you just deleted. There were no other intervening calls to new/delete.