0

I study C. I'm have simple code:

#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) says:

==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) Why? 2) How to fix it?

Deep
  • 2,472
  • 2
  • 15
  • 25
  • 1
    Well, i don't see any matching `fclose()`. – Sourav Ghosh Jan 09 '15 at 06:52
  • @SouravGhosh Not exactly.. I will go with John's answer. You can just go ahead as we see the purpose of the `my_fopen()` is to open the file stream and access it in the `main()` – Gopi Jan 09 '15 at 06:55
  • @Gopi I don't see how the usage of the file _justifies_ not performing `fclose()` before returning from `main()`. :-) – Sourav Ghosh Jan 09 '15 at 06:57
  • @SouravGhosh: Isn't said by standard that after returning from `main()` all open files get closed with a preseding `fflush()` or equalbehaving? So ofc this looks nasty, but is it really needed? – dhein Jan 09 '15 at 07:02
  • @Zaibis but the valgrind will report that as _possible_ leak, right ? [still reachable], IMO, if a file has been _opened_ by me, it _should_ be _closed_ by myself. :-) – Sourav Ghosh Jan 09 '15 at 07:05
  • Of course, just wasn't sure about anymore. – dhein Jan 09 '15 at 07:12

2 Answers2

1

you are opening a file but not closing the file, before returning from main. you can do

if ( 0 != my_fp )
  fclose(my_fp)
theadnangondal
  • 1,546
  • 3
  • 14
  • 28
0

Well, the problem here is not closing the file pointer before leaving main().

Just add

if (my_fp)
fclose(my_fp);

before return 0; in main().

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261