Red Hat axp-list: Linux on Alpha (1995-2022)
 help / color / mirror / Atom feed
From: Eric Smith <eric@brouhaha.com>
Subject: Re: fclose() (fwd)
Date: 22 Feb 1997 01:02:45 -0000	[thread overview]
Message-ID: <dee652a987f35d75402623490bb61367.axp-list@archive.invalid> (raw)

"Bryan W. Headley" <bheadley@interaccess.com> 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

             reply	other threads:[~1997-02-22  1:02 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
1997-02-22  1:02 Eric Smith [this message]
     [not found] <gaf@zk3.dec.com>
1997-02-21  4:59 ` fclose() (fwd) Bryan W. Headley
     [not found] <9702181221.AA02768@halfpint.rtp.avanticorp.com>
1997-02-18 16:14 ` Jerry Feldman
     [not found] <9702171536.ZM1175@davros.bwh.com>
1997-02-18 12:21 ` Jim Nance
  -- strict thread matches above, loose matches on Subject: below --
1997-02-17 22:55 Stephen Williams
     [not found] <jlnance@avanticorp.com>
1997-02-17 21:36 ` Bryan W. Headley
1997-02-17 21:18 Jim Nance
read-only archive

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox