0
#include <iostream>
using namespace std;
 
int * p1, * p2;  // Global int pointers
 
void allocate() {
   p1 = new int(88);     // Allocate memory, initial content unknown
           
   p2 = new int(99); // Allocate and initialize
}
 
int main() {
   allocate();
   cout << *p1 << endl;  // 88
   cout << *p2 << endl;  // 99
   delete p1;  
   delete p2;
   cout << *p1 << endl; 
   cout << *p2 << endl; 
   return 0;
}

// output
p1 88
p2 99
after delete
p1 17962984
p2 99

If I change my function to below, it gives still the same result.

void allocate() {
   p1 = new int;     
   *p1 = 88;         
   p2 = new int(99); 
}

Can someone tell me why p2 is still giving 99 even after I delete it?

I am new to this concept, a good reference would be appreciated.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Coder
  • 1,129
  • 10
  • 24
  • 1
    Your program has _undefined behavior_, that simple. – πάντα ῥεῖ Jul 24 '23 at 10:59
  • Yes, but i want to know why. i was expecting same for P1 and P2 – Coder Jul 24 '23 at 11:02
  • 4
    @Coder Undefined Behaviour is undefined. You cannot expect anything at all. Any result is equally valid, as well as crashing your program is valid, as well as making the result dependent on moon phase or making [demons fly out of your nose](http://catb.org/jargon/html/N/nasal-demons.html). When you have UB in your program, all assumptions are wrong. – Yksisarvinen Jul 24 '23 at 11:06
  • lol, i see. Thanks @Yksisarvinen – Coder Jul 24 '23 at 11:20

0 Answers0