So basically im writing code for a linkedList, but I keep getting a memoryLeak as a result of this code here. Could anyone help me find why, and also explain to me what im doing wrong?
struct Node* deleteNode(int data, struct Node* head){
struct Node* current = head;
struct Node* previous = NULL;
if(head == NULL){
return NULL;
}
while(current->data != data){
if(current->next == NULL){
return NULL;
}else{
previous = current;
current = current->next;
}
}
if(current == head){
struct Node* temp = head;
head = head->next;
free(temp);
}else
{
previous->next = current->next;
}
current = NULL;
return head;
}
You never call free()
on the deleted list node when its not the first element of your linked list.
You are getting a memory leak because you are not calling free
in the case where current != temp
. All you are doing in the else
portion is simply assigning previous->next = current->next
without deleting the current node.
You have already found the node you wish to delete using your while
loop, so add free(current)
after previous->next = current->next
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.