1

What i understand is if you use the "delete" operator on a pointer pointing to a memory address on the heap, it frees up the memory. I wrote this piece of code to test my knowledge but even after using the delete operator the memory address still has the value at the address. Can anyone please explain what is going on here?

#include <iostream>

using namespace std;

int main()
{
   int* aPtr = new int(5);
   cout << "address of int in heap is " << aPtr << endl;
   cout << "value of int in heap is " << *aPtr << endl;
   delete aPtr;
   cout << "address of int in heap is " << aPtr << endl;
   cout << "value of int in heap is " << *aPtr << endl;
   return 0;
}

The console output I got is here,

address of int in heap is 0x7fe851402700
value of int in heap is 5
address of int in heap is 0x7fe851402700
value of int in heap is 5
NoMan
  • 401
  • 1
  • 4
  • 10
  • 2
    Your code has undefined behaviour. – Kerrek SB Mar 23 '17 at 02:46
  • 3
    `delete` just makes the memory available for future use by `new`. Until you allocate something that reuses the same memory, and assign to it, nothing happens to the old memory. – Barmar Mar 23 '17 at 02:48
  • 1
    delete() does not zero the pointer. It simply frees the memory. That doesn't mean it stays valid; if you access it afterward, it's undefined what will happen. – Ken White Mar 23 '17 at 02:49
  • 1
    To elaborate on what Kerrek said, accessing `*aPtr` after `delete aPtr;` invokes undefined behavior. In most compilers, you will see the previous value (until the memory gets overwritten) but according to the standard, *anything at all* might happen when `*aPtr` is evaluated the second time. Note that the standard *does not indicate that the compiler may not zero or otherwise overwrite the memory allocated to the `int`* -- that's why it's undefined behavior. For example, when run under certain memory debuggers, they will leave behind traps that will (intentionally) crash on use-after-free. – cdhowie Mar 23 '17 at 02:49

0 Answers0