Valgrind找到指针指针的memleak

时间:2015-01-09 06:48:57

标签: c memory-leaks valgrind

我学习C. 我的代码很简单:

#include <stdio.h>
#include <unistd.h>


unsigned
my_fopen(FILE **fp, const char *file_name)
{
    *fp = fopen(file_name, "a"); // memleak here
    if (!*fp) {
        printf("Can't fopen file: %s\n", file_name);
        return 0;
    } else {
        return 1;
    }
}

int
main(int argc, char **argv)
{
    // begin only for -Wall -Werror -Wextra
    int p = 0;
    printf("Cnt: %d\n", argc);
    while (p < argc) {
        printf("Arg %d: %s\n", p, argv[p]);
        p += 1;
    }
    // end only for -Wall -Werror -Wextra

    FILE *my_fp;
    my_fopen(&my_fp, "./test.txt");

    return 0;
}

Valgrind(valgrind -v --track-originins = yes --trace-children = yes --leak-check = full ./test)说:

==960== HEAP SUMMARY:
==960==   in use at exit: 568 bytes in 1 blocks
==960==   total heap usage: 1 allocs, 0 frees, 568 bytes allocated

1)为什么? 2)如何解决?

2 个答案:

答案 0 :(得分:1)

您正在打开文件但未关闭文件, 从主要回来之前。你可以做到

if ( 0 != my_fp )
  fclose(my_fp)

答案 1 :(得分:0)

嗯,这里的问题是在离开main()之前没有关闭文件指针。

添加

if (my_fp)
fclose(my_fp);
return 0;之前的main()之前的