'deallocate memory from deleted node in Linked list
I am having a problem with memory leaking when I remove a node and I would appreciate some with some sort of work arround so that I wont leak when I remove element. BTW, if I just deallocate the linked list I am not leaking anything. Only when using the function to remove element.
This is how i call the functions:
remove_element(&head, create_node(input));
insert_sorted(&head, create_node(input));
Here are the main functions for this opperation:
struct link_list* create_node(char *input)
{
link_list* node = malloc(sizeof(tstr_node));
if (node == NULL)
{
exit(FAIL);
}
strcpy(node->data, input);
if (node->data== NULL)
{
exit(FAIL);
}
node->next = NULL;
return node;
}
int remove_element(link_list**head, link_list* node)
{
struct link_list *curr, *previous;
curr = *head;
previous = *head;
if(*head == NULL)
{
printf("List is already empty\n");
return FAIL;
}
else if(strcmp((char*)curr, (char*)node->data)==0)
{
*head = curr->next;
free(curr);
}
else
{
while(strcmp((char*)curr, (char*)node->data)!=0)
{
previous = curr;
curr = curr->next;
}
previous->next = curr->next;
free(curr);
}
return SUCCES;
}
int insert_sorted(link_list ** head, link_list * node)
{
link_list * curr;
if(*head == NULL || strcmp(((*head)->data), node->data) > 0)
{
node->next = *head;
*head = node;
return SUCCES;
}
else
{
curr = *head;
while( curr->next != NULL && strcmp(curr->next->data,node->data) < 0)
{
curr = curr->next;
}
node->next = curr->next;
curr->next = node;
return SUCCES;
}
return FAIL;
}
void deallocate(link_list** head)
{
link_list* curr = *head;
while(curr != NULL)
{
curr = curr->next;
free(*head);
*head = curr;
}
}
Solution 1:[1]
You're leaking the node that you created with create_node(input).
Simplest would be to change remove_element so it just takes the data string as the second argument, rather than a node. But if you can't do that, you need to assign this temporary node to a variable so you can free it.
link_list *temp = create_node(input);
remove_element(&head, temp);
free(temp);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
