Jeff
Jeff

Reputation: 12418

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!

Upvotes: 3

Views: 5159

Answers (4)

Greg Domjan
Greg Domjan

Reputation: 14115

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.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490338

It sounds like you're doing things exactly correctly -- fclose should reverse whatever fopen does, including freeing any resources it might allocate.

Upvotes: 0

JaredPar
JaredPar

Reputation: 755141

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.

Upvotes: 3

Etienne de Martel
Etienne de Martel

Reputation: 36984

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.

Upvotes: 6

Related Questions