Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two pointers referencing the same memory location, possible to make null if we deallocate the space?

If two pointers are referencing the same memory location. Will it be possible to make one pointer null, if we deallocate that memory location?

For example:

#include <iostream>
using namespace std;

class Node {
public:
    int value;
    Node(int k) : value(k) {}
};

int main() {
    Node* one = new Node(1);
    Node* two = one;
    
    delete one;
    one = nullptr;
    
    cout << two->value;
    
    return 0;
}

In the above code snippet, the output is 0. Shouldn't this crash or produce a null exception?

like image 875
GhostVaibhav Avatar asked Dec 03 '25 21:12

GhostVaibhav


1 Answers

Shouldn't this crash or produce a null exception?

Accessing a memory block after it has been freed/deleted will invoke undefined behavior.

This means that anything can happen. The program may crash or it may report an error. However, it may also behave as if the memory had not been freed/deleted.

If you want to increase the probability of such programming errors being detected and getting an error message, then I recommend that you run your program with a sanitizer, such as Valgrind or Address Sanitizer. However, this should generally only be done for debugging purposes, as this usually makes the program run significantly slower, due to many additional checks being performed.

like image 94
Andreas Wenzel Avatar answered Dec 05 '25 13:12

Andreas Wenzel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!