【问题标题】:C Set implementation using linked lists memory leakC Set 实现使用链表内存泄漏
【发布时间】:2017-04-11 23:24:40
【问题描述】:

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

【问题讨论】:

  • while(current != NULL)...current->next=new;。看起来 current 在最后一行是 NULL。
  • 不,当 current->next 为 null 时它会中断,因此 current 不为 null,它是这样编码的,因此只有一个元素的集合也会被检查

标签: c memory-leaks


【解决方案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
}

希望这会有所帮助。

【讨论】:

  • 如果malloc 失败,为什么还需要free?没有意义。
  • 哦,对不起,我的意思是说在你完成了你的值之后,你应该释放它,就像在 if 的末尾一样,我现在正在编辑它,谢谢。
  • 这对 OP 没有帮助。它分配一个新元素供以后使用的函数的点。因此,它并不意味着在那段代码中有free
  • 好点 kaylum,我们使用不同的函数来释放集合
猜你喜欢
  • 2021-08-21
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
  • 2012-12-13
  • 2017-09-26
  • 1970-01-01
相关资源
最近更新 更多