From mboxrd@z Thu Jan 1 00:00:00 1970 Message-ID: X-Archive-Original-Message-ID: <2.2.32.19970221222604.0167eda4@icarus.usanetworks.com> Date: 22 Feb 1997 01:02:45 -0000 From: Eric Smith Subject: Re: fclose() (fwd) "Bryan W. Headley" wrote: > That's incredibly stupid. Is this a /dev/null trick ("read all you want, > there's plenty of nothing for you"). Let's say I open /etc/passwd three times > and start reading records from each (but not necessarily synchronized; f1 > reads 20 bytes, f2 reads 30 bytes, f3 lseeks to the end of file - 50 bytes) > There's no way these three pointers can be to the same address; I think you missed the point of that test program. It opened and closed /dev/null three times sequentially; there were never two streams open to it at the same time. The point was that once you fclose() a stream, a later fopen() may return the same file pointer. There are at least two possible reasons for this. The FILE structures may be in a static array, and get reused, or they may be dynamically allocated, and it may just happen that the same space gets malloc'd again. This demonstrates why you should *never* fclose() a file twice. The original poster complained that fclose() should check whether the pointer is a valid file pointer, but that won't solve the problem if the same file pointer gets reused. > there's no excuse for fclose()ing one automagically closing another It doesn't. It's only when you do things with files after closing them that unpredictable things happen. ANSI (and presumably ISO) document that. > (esp. if you fclose, it twice, because, well, you're a fool, but you have > a license to be a fool on the wall) If you have a license to be a fool, you automatically get with it (at no extra charge) a license to have buggy code. If you can't keep track of whether you've closed a file or not, you should test the file pointer for NULL before attempting to close it, and set it to NULL after closing it. Cheers, Eric -- To unsubscribe: send e-mail to axp-list-request@redhat.com with 'unsubscribe' as the subject. Do not send it to axp-list@redhat.com