C中的内存泄漏与fopen

KWJ*_*104 1 c memory fopen valgrind memory-leaks

我有一个简单的程序,目前根据valgrind产生一些内存泄漏,我不知道为什么:

char *filename = strrchr(argv[3], "/") + 1;
file = fopen(fileName, "w");
Run Code Online (Sandbox Code Playgroud)

据我所知,我给程序一个argv [3]的"test/test2",第一行找到最后一次出现的"/",然后向前移动一个字符(到"t").然后第二行打开一个文件,该文件是char数组"test"的指针.

为什么会导致内存泄漏?

Yan*_*min 5

好吧,你的代码会泄漏文件句柄(后者fopen没有关闭).但是,如果没有更完整的例子,很难说清楚.


Jon*_*ler 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;
}
Run Code Online (Sandbox Code Playgroud)

它产生摘要输出:

==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
Run Code Online (Sandbox Code Playgroud)

随着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.
Run Code Online (Sandbox Code Playgroud)