1

the following code is supposed to free the dynamic memory of "num1" after the delete statement. I know it will still hold the memory address but what I don't understand is that why the old value "5" is still in there?

Sorry I'm still new to programming, hope you guys can help me out. Thank You :)

enter image description here

Omnik
  • 126
  • 1
  • 11

2 Answers2

3

Deleting the variable does not do anything to the memory. It simply says to the operating system "I am done using this memory space now and you are free to use it."

Quite honestly, printing a free'd variable is undefined behavior and you never know what will happen. Try running the same program an hour later and it may print out garbage or even crash.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
1

It is undefined behavior. It happened to have the same value at that memory address. But if you checked later the value may change. It is not as if as soon as you delete an object, the value at that address will be "reset" to zero, or something like that. It will simply stay at it's last value until some other object occupies that memory and writes a value there.

The value of an address that you did not allocate is undefined, period.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218