feelfree
feelfree

Reputation: 11763

Will forgetting to call std::ofstream close function lead to memory leak?

I am just curious about the question: Will forgetting to call std::ofstream close function lead to memory leak? I give the following example to illustrate my question:

using namespace std;
ofstream myfile;
myfile.open ("C:\\report.html");
myfile << "<html lang=\"en\"> " << endl;
myfile << "<head>" << endl;

Normallly, we should also call myfile.close() at the end of the code script. However, if I forgot to call the close function, what would happen? Will it lead to memory leak? I have used memcheck and valgrind in linux to check the program, and no memory leak can be found. So what is the side effect if the close function is not called.

Upvotes: 4

Views: 3206

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Will forgetting to call std::ofstream close function lead to memory leak?

Not in your situation: ofstream has a destructor, which takes care of cleaning up its resources when myfile goes out of scope. This is part of the technique called RAII (Resource Acquisition Is Initialization).

From the documentation:

Note that any open file is automatically closed when the fstream object is destroyed.

The close function is there to let you check if closing the file (or any other stream) has succeeded, and perform some additional file system cleanup in situations when close fails.

I have used memcheck and valgrind in linux to check the program, and no memory leak can be found.

That is a very solid indication that your program does not produce a memory leak.

Upvotes: 3

Wojtek Surowka
Wojtek Surowka

Reputation: 21003

If you do not call close explicitly the file will be closed when the object goes out of scope. So there is no danger of memory or other resource leak.

You may want to call close explicitly in order to check if the file closed properly. In many occasions the file will be written to only when it is closed, so checking the stream state after closing may be important.

Upvotes: 2

const_ref
const_ref

Reputation: 4096

When your std::ofstream object goes out of scope it will automatically be closed due to the use of RAII and the automatic calling of the object destructor.

In this situation your code is perfectly acceptable and would cause no memory leaks. There is no need to call close manually at all.

Only use close if you wish to reuse the object before it goes out of scope i.e if the ofstream object was a member of a class and you wish to re-use it then its possible to call close on it and then re-open it with a different file etc.

Upvotes: 5

David Schwartz
David Schwartz

Reputation: 182819

There is none. When the ofstream goes out of scope, it will be destroyed, closing it.

Imagine how hard it would be to use a container full of ofstreams if you had to make sure to close every one before allowing the container to go out of scope.

Upvotes: 3

Related Questions