[英]How come i keep getting a memory leak when i run this function in my C program?
So basically im writing code for a linkedList, but I keep getting a memoryLeak as a result of this code here.所以基本上我正在为 linkedList 编写代码,但是由于这里的代码,我一直在获取 memoryLeak。 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.当它不是链表的第一个元素时,您永远不会在已删除的列表节点上调用free()
。
You are getting a memory leak because you are not calling free
in the case where current != temp
.您正在获取 memory 泄漏,因为在current != temp
的情况下您没有调用free
。 All you are doing in the else
portion is simply assigning previous->next = current->next
without deleting the current node.您在else
部分所做的只是简单地分配previous->next = current->next
而不删除当前节点。
You have already found the node you wish to delete using your while
loop, so add free(current)
after previous->next = current->next
.您已经使用while
循环找到了要删除的节点,因此在previous->next = current->next
之后添加free(current)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.