Search code examples
c++file-iomemory-leaksfopenfclose

Does re-use of file pointers cause a memory leak?


It's been several years since I've dealt with C++, so bear with me...

I have a memory leak in my program which causes a run-time error. Could this be causing the error?

I have a global variable FILE *fp;

In a callback funciton, I have:

fp = fopen(filen,"w");
// do some writing
fclose(fp);

This process is repeated several times with the same pointer (fp). Is using the same file pointer a problem? Will fclose() automatically free up memory for me, or do I need to delete it manually? Are there any limitations that might cause a run-time error if I'm writing large quantities of text?

Thanks!


Solution

  • This approach won't cause any memory leaks so long as the fopen is always followed by a fclose before the nextfopen call.

    However if this is indeed what's happening I would question the need for a global variable. It's much safer overall to make this a local and pass it around to the functions which need to output information.