getline和strsep导致内存泄漏

时间:2015-02-24 00:27:26

标签: c memory-leaks

getlinestrsep一起使用时,会导致内存泄漏。我知道strsep会修改line - 这可能是原因吗? line未正确释放。

  FILE *file = fopen("keywords.txt", "r");
  if (file) {
    char* line = NULL;
    size_t len = 0;
    ssize_t read;

    while ((read = getline(&line, &len, file)) != -1) {  // Line 35

      char *token;
      while ((token = strsep(&line, "\t")) != NULL) {
        // Do stuff
      }

    }

    free(line);
    fclose(file);
  }

Valgrind回复:

==6094== 4,680 bytes in 39 blocks are definitely lost in loss record 7 of 7
==6094==    at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==6094==    by 0x51AEBB4: getdelim (iogetdelim.c:66)
==6094==    by 0x4009B3: read_keywords (main.c:35)
==6094==    by 0x400959: renew_init (main.c:64)
==6094==    by 0x400A48: main (main.c:68)

如果我评论strsep,那么就没有内存泄漏。

提示?

1 个答案:

答案 0 :(得分:10)

当您将&line传递给strsep时,它会更改line的值。在内循环结束时,line将为NULLfree(line)将不执行任何操作。这也会导致getline分配一个新的缓冲区,而不是重用当前的缓冲区。

您应该将line复制到新变量,例如char *line2 = line;并将&line2传递给strsep