E
Ertugrul Söylemez
Seebs said:In general, I agree. In practice, though, I don't see anything
intrinsically wrong with a system guaranteeing that certain classes of
resources are automatically deallocated on exit, and relying on that
behavior.
It is good that the operating system does that, but it's wrong to rely
on that feature.
How many people have you seen close stdout, stderr, and stdin at the
end of a program? Why don't they do that? You'd normally close any
file that was previously open, right?
You're not supposed to close the std-handles, because you have not
opened them. You are responsible for closing/freeing resources you have
opened/allocated yourself. For many resources there is even a stack of
allocations, which you should follow. The pattern looks like this:
<file1>
<file2>
<someCode />
<file3>
<someCode />
</file3>
<someCode />
</file2>
</file1>
As your main function is entered, there are already three of those file
tags open, one for each of stdin, stdout and stderr and possibly some
others. Closing one of the handles is the same as putting a closing tag
too early. Because of system peculiarities you may be forced to do
that, but it's better to avoid for the sake of consistency. Closing a
resource prematurely is just as wrong as closing it too late (or not
closing it at all).
That's also the reason I suggest freeing all of the allocated memory
before exiting. If you don't, there is a closing tag missing in your
program pattern. When you restructure your program, you might
accidentally forget that missing closing tag and introduce memory leaks.
You know how difficult it can be to find memory leaks, if you ever
notice them at all.
The CPS-based resource management function I proposed solves this
problem to some extent, because every resource has a clear scope, and
without abusing global/static variables, it can't even escape that
scope. In other words, the closing tag is enforced in the pattern.
Greets
Ertugrul