+ 1

Delete Operator not working? C++ (Help)

So... i'm learning C++ and something strange is occurring here on this code: int main() { 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: delete x; delete y; cout << " x: " << *x <<endl; //outputs random value cout << " y: " << *y <<endl; //outputs 6 (???) // Y is not deleting ???????? return 0; } 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.

22nd Mar 2020, 11:59 AM
Yandra V.
Yandra V. - avatar
1 Answer
+ 6
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.
22nd Mar 2020, 12:40 PM
Dennis - avatar