使用getline和strsep发生内存泄漏 [英] Memory leak with getline and strsep

查看:135
本文介绍了使用getline和strsep发生内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时使用getlinestrsep会导致内存泄漏.我知道strsep修改了line-这可能是原因吗?该line无法正确释放.

Get a memory leak while using getline together with strsep. I know strsep modifies line - could this be the cause? That line is not freed correctly.

  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返回此:

Valgrind returns this:

==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注释掉,则不会发生内存泄漏.

If I comment out strsep, there's no memory leak.

提示?

推荐答案

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

When you pass &line to strsep, it will change the value of line. At the end of the inner loop, line will be NULL and free(line) will do nothing. This will also cause getline to allocate a new buffer instead of reusing the current one.

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

You should copy line to a new variable, e.g. char *line2 = line; and pass &line2 to strsep.

这篇关于使用getline和strsep发生内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆