我有一个简单的程序,目前根据valgrind产生一些内存泄漏,我不确定原因:
char *filename = strrchr(argv[3], "/") + 1;
file = fopen(fileName, "w");
据我所知,我给程序一个argv [3]的“test / test2”,第一行找到最后一次出现的“/”,然后向前移动一个字符(到“t” )。然后第二行打开一个文件,该文件是char数组“test”的指针。
为什么会导致内存泄漏?
答案 0 :(得分:5)
好吧,你的代码会泄漏文件句柄(后者fopen没有关闭)。但是,如果没有更完整的例子,很难说清楚。
答案 1 :(得分:5)
如果使用打开的文件流,标准I / O库很可能会为流分配缓冲区。如果您没有明确关闭流,valgrind
很可能会将该内存视为仍在使用中;有可能被视为泄露的外部机会。
来自valgrind
的确切消息是什么?你为什么指着fopen()
?
考虑这个简单的程序:
#include <stdio.h>
static void leaky(void)
{
FILE *fp = fopen("/etc/passwd", "r");
char buffer[2048];
while (fgets(buffer, sizeof(buffer), fp) != 0)
fputs(buffer, stdout);
/* fclose(fp); */
}
int main(void)
{
leaky();
return 0;
}
它产生摘要输出:
==6169==
==6169== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 5 from 1)
==6169== malloc/free: in use at exit: 568 bytes in 1 blocks.
==6169== malloc/free: 1 allocs, 0 frees, 568 bytes allocated.
==6169== For counts of detected errors, rerun with: -v
==6169== searching for pointers to 1 not-freed blocks.
==6169== checked 69,424 bytes.
==6169==
==6169== LEAK SUMMARY:
==6169== definitely lost: 0 bytes in 0 blocks.
==6169== possibly lost: 0 bytes in 0 blocks.
==6169== still reachable: 568 bytes in 1 blocks.
==6169== suppressed: 0 bytes in 0 blocks.
==6169== Reachable blocks (those to which a pointer was found) are not shown.
==6169== To see them, rerun with: --show-reachable=yes
如果未注释掉fclose(fp)
,则输出为:
==7125==
==7125== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 5 from 1)
==7125== malloc/free: in use at exit: 0 bytes in 0 blocks.
==7125== malloc/free: 1 allocs, 1 frees, 568 bytes allocated.
==7125== For counts of detected errors, rerun with: -v
==7125== All heap blocks were freed -- no leaks are possible.