我是学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/