0

Can anyone guide me through the code? I'm not sure how the delete is supposed to work. How am I still able to modify the content of the heap memory even after deallocation?

#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
  cout << "------ Introducing Heap mem allocation ------" << endl;

  int *p = new int; // allocation
  *p = 1114; //set the content

  cout << p << "   " << *p << endl; //check the address p holds and the content

  delete p; // What happens here? Shouldn't the address held by p get deleted?
  cout << p << "   " << *p << endl; // this produces no change except that the content is set to 0

  *p = 20; // but I can still modify the content
  cout << p << "   " << *p << endl; // What am I missing? How does 'delete' actually work? HELP

  return 0;
}
Theos
  • 1
  • 3
  • 4
    You are accessing memory that doesn't belong to you anymore which is undefined behavior. Accessing `*p` might cause a crash or a bluescreen or just work or have any number of other effects. – nwp Mar 16 '17 at 14:36
  • Thanks for the insight. Is it expected for `p` to retain the address of the allocated heap memory even after `delete`? – Theos Mar 16 '17 at 14:53
  • _" Is it expected for p to retain the address of the allocated heap memory even after delete?"_ Yes – Richard Critten Mar 16 '17 at 14:56
  • p still points at the memory, but the memory is "de-allocated". It retains the value until something requests new memory and it gets over-written. – Jason Lang Mar 16 '17 at 14:57
  • btw, they don't zero the pointer or scrub the memory, because that would waste time. It's all about speed. – Jason Lang Mar 16 '17 at 14:57
  • @JasonLang So in essence `delete` makes the program revoke the control of heap memory right? Is there anything else to it? – Theos Mar 16 '17 at 15:31

0 Answers0