2017-04-11 122 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