0

In the below code, memory is allocated for an integer and later a shallow copy is being made and finally delete is being called on it. How does it still print 23 as the output and why doesn't the delete call on q, cause a run time exception.

#include <iostream>

using namespace std;

int main() {
    int* p = new int(23);
    int* q = p;

    delete p;
    cout << *p << endl;
    delete q;


    return 0;
}
Tousif
  • 53
  • 1
  • 6

1 Answers1

1

Undefined behaviour means anything can happen.

It might crash.

It might crash your car.

It might crash your brain.

It might crash Sagittarius A* into your brain.

It might crash your brain into your car, then crash them both into Sagittarius A*.

It might appear to work.

But it's still undefined.

Don't expect results.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055