Does re-use of file pointers cause a memory leak?
It's been several years since 开发者_StackOverflow社区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!
Yes, fclose
releases all resources associated with the FILE *
. As a rule of thumb, only use free
on what was allocated with malloc
, and only use delete
on what was allocated with new
.
And you're never "reusing" the same pointer: a call to fopen
will return a new FILE *
.
By the way, since you're doing C++, consider looking into fstream
. It'll handle the resource management for you.
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.
It sounds like you're doing things exactly correctly -- fclose
should reverse whatever fopen
does, including freeing any resources it might allocate.
Multiple threads hitting the same global could cause an issue that would appear after one of the threads closed the file.
Opening the file a subsequent time and changing the file pointer wouldn't be seen when it happened.
Closing the file would only close 1 of the created file handles leaving a file handle leak and any further writes to the file would fail and a subsequent close file on the same handle trying to close it a second time would likely crash if it didn't already happen writing to the file.
精彩评论