【发布时间】:2016-03-29 19:55:27
【问题描述】:
我尝试使用带有以下选项的 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->next = temp; curr = temp;会做什么? -
尝试使用
curr->next = temp; curr = curr->next;我也在我的系统上编译了它,它工作正常。您使用的是哪个操作系统? -
您将 temp 设置为 NULL,然后调用 free()。颠倒顺序。就是这样,在循环内部调用 malloc,然后在外部释放,所以......还有其他控制流问题需要解决。
-
这只是createList函数吧?你也有freelist吗?您是在 main 中调用它吗?
-
使用调试符号将行号添加到您的 valgrind 输出中。使用
gcc -g
标签: c memory-leaks linked-list valgrind