Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++: Program for Deleting a node and return its right child:

I was attempting to solve the question for deleting a node in BST, and saw a strange output. In the case where node has only right child, I was trying to delete that node and return its right child. Somehow, both of the codes below gave the correct result, even though it seems to me like only code 1 should work since we’re trying to access a deleted node.
Can someone tell me why this happens?

cpp
Code 1:

Node* temp = root->right;
delete root;
return temp;

Code 2:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Node* temp = root;
delete temp;
return root->right;

>Solution :

The result of dereferencing a deleted pointer is undefined. That means anything can happen, including having a program appear to work.

There is no promise that an exception will be thrown, or that an error message will be displayed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading