c - Valgrind 发现指针的 memleak

标签 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-origins=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)如何解决?

最佳答案

您正在打开一个文件但没有关闭该文件, 从 main 返回之前。你可以做

if ( 0 != my_fp )
  fclose(my_fp)

关于c - Valgrind 发现指针的 memleak,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27855255/

相关文章:

c - 如何在 C 中将 stdout 设置为完全缓冲?

memory-leaks - valgrind memcheck 报告误报?

c++ - CRT 不打印内存泄漏的行号

c++ - C++ 数组释放期间的段错误

pointers - C - 错误是 "free(): invalid next size (normal) "

康威的生命游戏 : extraneous cells being printed when program run with only blank/dead cells (C/SDL2)

c++ - 频繁访问文件映射内存

c++ - 运送仅暴露 C api 的 C++ dll

c# - 解决C#内存泄漏的方法有哪些

c++ - Valgrind C++ : Invalid Read Of Size 8