0

If deleting the pointer, why is the output 5 5?(I'm new)

#include <iostream>
using namespace std;

int main(){
    int* i = new int(5);

    cout<< *i <<endl;
    delete i;
    cout<< *i <<endl;
    return 0;
}
Argon
  • 752
  • 7
  • 18
LasuEr
  • 11
  • 3
  • 3
    It's not strange. `delete` simply deallocates the memory. It doesn't clear out that memory region. Hence you can see the contents of that memory location being retained until some other part of your program rewrites it. You can read more about `delete` keyword [here](http://www.cplusplus.com/reference/new/operator%20delete/). – Argon Jun 19 '21 at 12:58
  • 4
    The second `cout<< *i < – Eljay Jun 19 '21 at 12:58
  • Argon's answer was enough. Thanks. – LasuEr Jun 19 '21 at 13:19
  • You can accept the answer to mark your question as solved. This is done by clicking the tick mark to the left of the answer. – Ruslan Jun 19 '21 at 13:19

1 Answers1

2

Delete doesn't set 0 or any value to the memory i is pointing to. It just flags it as free so something can use it later. This leads to undefined behaviour

Dusan Todorovic
  • 472
  • 2
  • 12