getline()发生内存泄漏,请使用valgrind

时间:2018-07-19 04:29:31

标签: c memory-management memory-leaks valgrind

这是我的代码的骨架:

int main (int argc, char* argv []) {   
  int  n, offset, offset1;
  int error = 0;
  char *buf = NULL;
  size_t len = 0;
  char load_var[] = "load";

  while(getline(&buf, &len, stdin) > 0) {
    char cmd[65] = "";
    while ((n = sscanf(buf,"%64s%n",cmd, &offset)) > 0) {
      if (!strcmp(cmd,load_var)) {
        char str[65] = "";
        char another_str[65] = "";
        int var_num;
        buf += offset;
        if ((var_num = sscanf(buf,"%64s%n%64s%n",str,&offset, another_str, &offset1)) > 0) {
          some_function(str);                    
        }

        buf += offset;
      }
    }
  }

  free(buf);

  return error;
}

Valgrind返回消息:

==15414== 120 bytes in 1 blocks are definitely lost in loss record 1 of 1
==15414==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15414==    by 0x4EA5F54: getdelim (iogetdelim.c:66)
==15414==    by 0x401B3B: main (dev.c:177)

我不知道我在哪里使用getline()错了,所以程序出现了内存错误。

1 个答案:

答案 0 :(得分:0)

此评论是正确的答案:

buf += offset
  

,它将在后续的getline调用中调用未定义的行为,并最终释放。坦白说,我很惊讶这不会崩溃。 – WhozCraig

Valgrind还应在报告泄漏之前报告“无效的重新分配”或类似的