Re: Closing the FILE object.

From: Michael Poole (poole@troilus.org)
Date: Fri Jul 14 2000 - 12:52:08 EST


"Richard B. Johnson" <root@chaos.analogic.com> writes:

> This is in reference to the reported seg-faults when attempting to
> fclose() an invalid file pointer.
>
> The following shows that my current 'C' runtime library does not
> adhere to any known standard when referencing the FILE object during
> fclose(). This is gcc 2.7.2.3 (libc 5.3.12)
>
> According to existing Linux documentation, this should return
> EBADF. It should NOT seg-fault.
>
> #include <stdio.h>
> #include <malloc.h>
>
> int main ()
> {
> FILE *fp;
> fp = (FILE *)malloc(sizeof(FILE));/* Make sure the pointer is valid */
> fprintf(stderr, "%p\n", fp); /* Display valid address */
> fclose(fp);
> puts("It worked??"); /* Will not occur */
> return 0;
> }

Don't you remember what happened the last time you tried to treat
FILE* as something besides an opaque pointer? I thought Uli Drepper
was clear in his explanation that you're not allowed to do that and
expect consistent results. A FILE* may have arbitrary state inside of
it, and if you didn't get the FILE* from an fopen() type call (or as
stdin, stdout, stderr), then you can't expect fclose() to work.

In fact, if you even THOUGHT about it, you'd see that your example is
pretty stupid. A FILE* stream is supposed to have a buffer. If the
thing pointed to by FILE* contains a pointer to that buffer, then you
just gave fclose() something with illegal state. There are a number
of other reasons that you should not expect an arbitrary FILE* to be
acceptable to fclose().

Further, I don't think the standard even mandates that FILE by itself
be meaningful. If FILE is typedef'ed as char, no interface would
break (although warnings would be harder to diagnose), but your code
above would (rightly) break the stdio.h implementation.

I don't know what standard you think mandates that library functions
protect the user against severe user boneheadedness, but if you want
to write sane code, you shouldn't do boneheaded things.

Michael

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.rutgers.edu
Please read the FAQ at http://www.tux.org/lkml/



This archive was generated by hypermail 2b29 : Sat Jul 15 2000 - 21:00:20 EST