Weird pointer situation I don't understand

I'm a bit confused about the output of the following code:

1
2
3
4
5
6
7
8
    char* a = new char;
    char* b = a;
    *b = 'Z';
    cout << *b << *a << endl;
    delete(a);
    a = new char;
    *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'?
Last edited on
> 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.
1
2
    delete(a);
    a = new char;


Some 'debug' allocators force each new allocation to come from fresh memory, and fill all deleted memory with a fixed pattern, to aid with the detection of any use-after-free issues.
https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations

I see now! Thanks for the information! :)
Topic archived. No new replies allowed.