使用getline和strsep发生内存泄漏 [英] Memory leak with getline and strsep
问题描述
同时使用getline
和strsep
会导致内存泄漏.我知道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屋!