CBFalconer <> writes:
> lihua wrote:
> >
> > We all know that fclose() must be called after file operations to
> > avoid unexpected errors.But there are really cases when you forget
> > to do that!
Be careful when you use FILE objects then
> > Just like what happens in memory operations, everyone knows the
> > importance of freeing the allocated memory, but there do have memory
> > leaks from time to time! For the memory leak case, there are lots of
> > testing tools to detect it automatically like Rational Purify or
> > other free ones.
> >
> > So my question is: is there any testing tool right there which can
> > detect forgetting-fclose defects automatically?
>
> If you keep track of what you are doing there should be no
> problem. However if you need to protect against your own
> sloppiness, try this:
>
> 1. Wherever you declare the FILE* variable, initialize it to NULL.
This is almost very good advice, but it's just a half-measure though and
hardly a solution to the real problem which is sloppiness when using
FILE objects. Initializing FILE pointers to NULL when they are
declared, i.e. with something like this:
1 #include <stdio.h>
2
3 int main(void)
4 {
5 FILE *fp = NULL;
6 int k;
7
will only serve as a warning the first time `fp' has to be accessed.
If the `fp' pointer is used in a loop and gets assigned to the result of
multiple fopen() calls, the second and all subsequent calls will not
have a NULL `fp' as an indication of something that is wrong with the
program:
8 for (k = 1; k < argc; k++) {
9 if (argv[k] == NULL)
10 continue;
11 fp = fopen(argv[k], "rb");
12
13 /* Do something with `fp' here. */
14
15 /* Missing fclose() call. */
16 }
17
18 return (EXIT_SUCCESS);
19 }
The only way to avoid leaking open FILE objects here is to be careful
when writing the program.
Instead of the original suggestion (Wherever you declare the FILE*
variable, initialize it to NULL), I usually prefer to "initialize
pointers to known values right before you start using them and use
assert() to watch out for 'strange' values in strategically chosen
places".
- Giorgos