I am learning cpp. I was learning how to insert elements in bst and got confused on when to use "delete" to free the memory allocated by new:
Here is my program
Node * insert(Node * root, int data) {
Node * temp;
Node * prev;
Node * newnode = new Node(data);
if(root == nullptr)
{
root = newnode;
}
else
{
temp = root;
while(temp!=NULL/*temp->left != NULL || temp->right!=NULL*/ )
{
prev = temp;
if(newnode->data > temp->data)
{
temp = temp->right;
}
else
{
temp = temp->left;
}
}
if(prev->data > newnode->data){prev->left = newnode;}
else
{
prev->right = newnode;
}
}
**//delete newnode**;(if I use delete , root becomes dangling (if I guess correctly) and program crashes)
cout<<"returning root "<<root->data;
return root;
}
};
The Node class definition is
class Node {
public:
int data;
Node *left;
Node *right;
Node(int d) {
data = d;
left = NULL;
right = NULL;
}
};
If I dont use delete
, program works fine but I understand it causes memory leak and want to learn to avoid that in such scenarios Thank you in advance.
Aucun commentaire:
Enregistrer un commentaire