1

I have a simple piece of a program thats currently producing some memory leaks according to valgrind and I'm not sure why:

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

So as far as I know, I give the program an argv[3] of "test/test2", and the first line finds the last occurrence of "/", and then moves one character forward (to "t"). Then the second line opens a file that is a pointer to the char array "test".

Why is this causing a memory leak?

KWJ2104
  • 1,959
  • 6
  • 38
  • 53

2 Answers2

10

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.
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
5

Well, your code would leak a file handle (the latter fopen is not closed). However, without a more complete example its hard to tell.

Yann Ramin
  • 32,895
  • 3
  • 59
  • 82