This topic is 3738 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hello, I'm trying to implement a double linked list, but I'm having some problems with the deletion of a node:
void *remove_node(node_t *lst, node_t *node)
{
void *temp = node - > data;

if(node - > previous != NULL)
node - > previous - > next = node - > next;
else if(node - > next != NULL)
*lst = * node - > next;

if(node - > next != NULL)
node - > next - > previous = node - > previous;

free(node);
return temp;
}

I'm getting double frees when I consecutively delete nodes that are on the first position of the list (that is, the previous node is NULL).
Whats wrong with my code?

Thank You,
jjoi



Share on other sites
The code breaks in the case where you handle deleting the head of the list. When you try to readjust the head pointer, you are modifying a local copy of the head pointer.

The following should work. I have also taken the courtesy of re-writing the code with clearer logic:

void remove_node(node_t** headOfList, node_t* nodeToDelete ){     if(nodeToDelete == *headOfList)     {        *headOfList = noteToDelete->next;     }     if(nodeToDelete->previous != NULL)     {        nodeToDelete->previous->next = nodeToDelete->next;     }     if(nodeToDelete->next != NULL)     {         nodeToDelete->next->previous = nodeToDelete->previous;     }     free(nodeToDelete);}

Notice the type of the first argument is node_t**, thats where your previous code breaks down.

Share on other sites
Quote:
 Original post by fpsgamerThe code breaks in the case where you handle deleting the head of the list. When you try to readjust the head pointer, you are modifying a local copy of the head pointer.The following should work. I have also taken the courtesy of re-writing the code with clearer logic:*** Source Snippet Removed ***Notice the type of the first argument is node_t**, thats where your previous code breaks down.

That makes sense!
Problem solved!
Thanks! :D