Valgrind 坚称该函数存在内存泄漏,但我无法找到它。这是在 c 中使用链表实现集合的一部分。
int set_add(set * s,int e[2]){
if(set_empty(*s)) {
element * new=malloc(sizeof (element));
new->coord[0]=e[0];
new->coord[1]=e[1];
new->next =NULL;
s->head=new;
return 1;
}
element * current=s->head;
while(current != NULL) {
if(coord_equal(current->coord,e)) {
return 0;
}
if(current->next ==NULL){
break;
}
current=current->next;
}
element * new=malloc(sizeof (element));
new->coord[0]=e[0];
new->coord[1]=e[1];
new->next = NULL;
current->next=new;
return 1;
}
最佳答案
我认为正确的做法是在每次 malloc 之后验证它是否确实被分配,如果没有,您应该释放该内存区域并退出该函数。
类似这样的事情:
value = malloc();
if (value){
//value was allocated correctly
//do the things you want with it
free(value);
}
else{
return 0; //exit your function
}
希望这有帮助。
关于使用链表的C Set实现内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43357791/