我尝试使用带有以下选项的 valgrind 检查内存泄漏:
valgrind --leak-check=full -v ./linkedlist2
Valgrind 说 createList()
函数中存在内存泄漏,但我找不到原因。能否请您帮助我了解内存泄漏的原因是什么?
相关代码:
struct node{
int data;
struct node* next;
};
struct node* createList(int num)
{
struct node* temp = NULL;
struct node* head = NULL;
struct node* curr = NULL;
int i = 0;
if(num <= 0)
{
printf("Invalid size for createList\n");
return;
}
for(i=0;i<num;i++)
{
temp = malloc(sizeof(struct node)); //allocate memory
temp->data = i+1;
temp->next = NULL;
if(i == 0)
{
head = temp;
curr = temp;
}else {
curr->next = temp;
curr = temp;
}
}
curr = temp = NULL;
//curr->next = temp->next = NULL;
free(curr);free(temp);
return head;
}
最佳答案
这一行导致了问题
curr = temp = NULL;
//curr->next = temp->next = NULL;
free(curr);free(temp);
好吧,在这里您将 NULL
分配给结构节点指针 curr
和 temp
,此后它指向的内存将变成垃圾。您首先使用 free()
释放内存并将其分配给 NULL
用这个替换你上面的代码
free(curr);
free(temp);
curr = temp = NULL;
关于c - CreateList 函数(链表)中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34434690/