Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Explain briefly how to fix the memory leak in the insert implementation below. A

ID: 3596963 • Letter: E

Question

Explain briefly how to fix the memory leak in the insert implementation below. Assume that the destructor is implemented correctly. Note that there is no bug in insert other than the memory leak. Numbers on the left give line numbers.

1 bool BSTInt: :insert (int item) 3 BSTNodeInt* newNode-new BSTNodeInt (item) 4 if (!root) root = newNode ; ++isize; return true; 6 10 BSTNode Int* curr = root; 11 while (curr != nullptr) 12if (itemdata) 13 if (curr->left nullptr) ( curr->left = newNode ; newNode->parent = curr; return true; 15 16 17 18 19 20 21 22 else if (curr->data left; if (curr->right nullptr) t curr-right newNode ; newNode->parent = curr; return true; else [ curr curr->right; // found the value. Nothing to insert return false; 34 35

Explanation / Answer

In the else statement at line 28 you are saying that the value is found and no need to insert. But you have created a BST node for that at line 3 and not used. So you have delete that node pointer.

So delete the created pointer if item is already there in the BST.

That means delete the created pointer in the else block at line 28. Other than that there are no other memory leaks.

So your else block at line 28 looks as follows :

---------------------------------------------------------------

else {

delete newNode; /* newNode created at line 3 */

}

--------------------------------------------------------------

In this way memory leak is solved.

/* hope this helps */

/* if any queries please comment */

/* thank you */

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote