So... i'm learning C++ and something strange is occurring here on this code:
int *x = new int;
int *y = new int;
*y = 6;
*x = 5;
cout << " X Memory Adress: " << x <<endl;
cout << " Y Memory Adress: " << y <<endl;
cout << " X value: " << *x <<endl; //outputs 5
cout << " Y value: " << *y <<endl; //outputs 6
// Now delete the values:
cout << " x: " << *x <<endl; //outputs random value
cout << " y: " << *y <<endl; //outputs 6 (???)
// Y is not deleting ????????
When i try to delete Y, it still showing me it's value.
But here's the thing, if i change the order of deleting ( first Y, after X ), the X value still showing up and Y value is deleted.
Please, someone show me the light.
delete simply releases the allocated memory.
All it does it set a flag telling the memory area it is free so that other processes can use the memory.
It does not zero out the memory or anything else, the previous value is still there because it's a waste of cpu time to do so.
You'll have to zero it out yourself before deleting it if you really want to.
Accessing the memory after deletion like you're doing here is undefined behaviour, anything can show up.