【发布时间】:2021-01-31 01:01:32
【问题描述】:
我有一个关于函数getline() 的问题,正如valgrind 所报告的那样,它在两种内存使用情况下的行为似乎有所不同。我发布了两种情况的代码并解释了行为。
我希望有人能指出我正确的方向。
第一种情况
getline() 在 while 循环中调用,读取缓冲区中文本文件的所有行。然后在循环结束时只释放一次缓冲区:在这种情况下,valgrind 不会出现错误(不会发生泄漏)。
int main(int argc, char* argv[])
{
char* buffer = NULL;
size_t bufsize = 0;
ssize_t nbytes;
int counter = 0;
char error = 0;
FILE* input_fd = fopen(argv[1], "r");
while ((nbytes = getline(&buffer, &bufsize, input_fd)) != -1)
{
counter += 1;
}
free(buffer);
fclose(input_fd);
return 0;
}
第二种情况
同一循环调用一个函数,该函数又调用getline(),传递相同的缓冲区。同样,缓冲区仅在循环结束时被释放一次,但在这种情况下,valgrind 报告了内存泄漏。事实上,让程序运行并查看 RSS,我可以看到它随着循环的进行而增加。请注意,在循环内添加一个空闲(每个循环释放缓冲区)问题就消失了。这是代码。
int my_getline(FILE* lf_fd, char** lf_buffer)
{
ssize_t lf_nbytes = 0;
size_t lf_bufsiz = 0;
lf_nbytes = getline(lf_buffer, &lf_bufsiz, lf_fd);
if (lf_nbytes == -1)
return 1;
return 0;
}
int main(int argc, char* argv[])
{
char* lf_buffer = NULL;
size_t bufsize = 0;
ssize_t nbytes;
int counter = 0;
int new_line_counter = 0;
char error = 0;
FILE* lf_fd = fopen(argv[1], "r");
while ((my_getline(lf_fd, &lf_buffer)) == 0)
{
// Added to allow measuring the RSS
sleep(2);
// If I uncomment this, no memory leak occurs
//free(lf_buffer);
}
free(lf_buffer);
fclose(lf_fd);
return 0;
}
Valgrind 输出
==9604== Memcheck, a memory error detector
==9604== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==9604== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==9604== Command: ./my_getline_x86 /media/sf_Scambio/processes.log
==9604== HEAP SUMMARY:
==9604== in use at exit: 1,194 bytes in 2 blocks
==9604== total heap usage: 8 allocs, 6 frees, 11,242 bytes allocated
==9604==
==9604== 1,194 bytes in 2 blocks are definitely lost in loss record 1 of 1
==9604== at 0x483DFAF: realloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-
linux.so)
==9604== by 0x48E371D: getdelim (iogetdelim.c:102)
==9604== by 0x1092B3: my_getline (my_getline.c:14)
==9604== by 0x10956A: main (my_getline.c:38)
==9604==
==9604== LEAK SUMMARY:
==9604== definitely lost: 1,194 bytes in 2 blocks
==9604== indirectly lost: 0 bytes in 0 blocks
==9604== possibly lost: 0 bytes in 0 blocks
==9604== still reachable: 0 bytes in 0 blocks
==9604== suppressed: 0 bytes in 0 blocks
==9604==
==9604== For lists of detected and suppressed errors, rerun with: -s
==9604== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
【问题讨论】:
标签: c memory-leaks valgrind getline