Re: Write to a closed stream bug.

randy thelen (rthelen@netapp.com)
Thu, 18 Dec 1997 10:45:45 -0800


> Imagine the following code:
>
> 1: FILE *s1, *s2;
> 2:
> 3: s1 = fopen ("foo", "rw"); /* s1 gets assigned */
> 4: fwrite ("Hello", 1, 5, s1);
> 5: fclose (s1); /* after this, the system is
> 6: free to do whatever it wants
> 7: with the memory pointed to
> 8: by s1 */
> 9: s2 = fopen ("bar", "rw"); /* actually, it gets assigned
> 10: to s2, so s1 and s2 now
> 11: refer to the same memory */
> 12: fwrite ("World", 1, 5, s1); /* Ooops, s1 now writes to
> file bar!!!! */

Thank you Joerg for making it so clear. Yes, the problem is that the
semantics of the fclose call allow the caller to make the above mistake.

And, worst yet, no solution fits all cases.

And, no, you probably do not want:

fclose(&s1)

nor would you want

s1 = fclose(s1) /* because here (void) fclose(s1) would compile and run */

Nor would you want to hand out indexes into a list (because how large
would the list become?).

What I mean to say is if you like any of the above solutions, you can
create your own library implementing it and use it. That's one of the
beauties of the un*x style operating system: Build your own interfaces from
the atoms that exist. But use those atoms carefully, lest you damage yourself
or others.

-- Randy