1

I am trying to understand memory management in C++.
Here's my code:

 Person *P5 = new Person();
 delete P5;
 std::cout<<P5->getWeight()<<std::endl;
 delete P5;
 std::cout<<P5->getWeight()<<std::endl;

My first cout works and the 2nd doesn't,where as I used delete before both. Can anyone explain this?

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Parth Mody
  • 438
  • 1
  • 5
  • 17

2 Answers2

3
delete P5;
std::cout<<P5->getWeight()<<std::endl; // 1
delete P5;                             // 2
std::cout<<P5->getWeight()<<std::endl; // 3
  1. You're trying to dereference pointer that points to already realized memory. This is Undefined Behavior. Anything could happen.

  2. You're trying to free already freed memory. This is Undefined Behavior. Anything could happen.

  3. goto 1

awesoon
  • 32,469
  • 11
  • 74
  • 99
2

Neither cout is guaranteed to work for you, since you use a deleted object.
It's just that sometimes, when you delete something, the memory is not overwrited, the data is still there. But it may be reused next time you allocate memory.
When you do

 Person *P5 = new Person();
 delete P5;

p5 is a dangling pointer. Just don't use it after delete

spiritwolfform
  • 2,263
  • 15
  • 16