2017-04-11 124 views
-1

Valgrind坚持认为这个函数有内存泄漏,但我无法找到它。这是c中使用链接列表的集合实现的一部分。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; 
} 
+1

'while(current!= NULL)'...'current-> next = new;'。在最后一行看起来'current'为NULL。 – kaylum

+0

当current-> next为空时,它会中断,因此current不是null,它被编码,以便只检查一个元素的集合。 –

回答

-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 
} 

希望这有助于。

+0

如果malloc失败,为什么需要'free'?没有意义。 – kaylum

+0

哦,对不起,我的意思是说,在你完成了你的价值后,你应该释放它,就像现在正在编辑它,谢谢。 –

+0

这对OP没有帮助。它为它分配一个新元素以备后用的功能。所以这并不意味着在那段代码中有一个'free'。 – kaylum