If you use the opened file stream, there's a good chance that the Standard I/O library will allocate a buffer for the stream. If you don't explicitly close the stream, there's a good chance that valgrind
will regard that memory as still in use; there is an outside chance it would be regarded as leaked.
What is the exact message from valgrind
? Why are you pointing at fopen()
?
Consider this trivial program:
#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;
}
It produces the summary output:
==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
With the fclose(fp)
not commented out, the output is:
==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.