From owner-freebsd-questions Mon Jun 7 0:33:40 1999 Delivered-To: freebsd-questions@freebsd.org Received: from lanfear.nidlink.com (lanfear.nidlink.com [216.18.128.7]) by hub.freebsd.org (Postfix) with ESMTP id C102D152CC for ; Mon, 7 Jun 1999 00:33:35 -0700 (PDT) (envelope-from malpert@holdenz.com) Received: from enaila.nidlink.com (root@enaila.nidlink.com [216.18.128.8]) by lanfear.nidlink.com (8.9.0/8.9.0) with ESMTP id AAA21356; Mon, 7 Jun 1999 00:33:32 -0700 (PDT) Received: from hal.bsdguy.com (tnt132-176.nidlink.com [216.18.132.176]) by enaila.nidlink.com (8.9.0/8.9.0) with ESMTP id AAA20914; Mon, 7 Jun 1999 00:33:30 -0700 (PDT) Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 8bit MIME-Version: 1.0 Message-ID: X-Mailer: XFMail 1.3 [p0] on FreeBSD X-Priority: 3 (Normal) In-Reply-To: Date: Mon, 07 Jun 1999 00:37:40 -0700 (PDT) Reply-To: malpert@holdenz.com From: Shawn Workman To: freebsd-questions@freebsd.org Subject: RE: Possible C library bug? Sender: owner-freebsd-questions@FreeBSD.ORG Precedence: bulk X-Loop: FreeBSD.ORG On 07-Jun-99 Bryce Newall wrote: > Greetings! > > One of my users recently brought to my attention a possible bug in either > the FreeBSD C compilers (cc and gcc), or one of the libraries. The bug > has to do with attempting to close a file that was never successfully > opened. In other words, with a statement something like: > > f = fopen("filename", "r"); > > If the fopen fails, for whatever reason, and f has a value of NULL, then > this statement: > > flose(f); > > will return a segmentation fault, instead of simply not doing anything. > > Here is a piece of code that he wrote to test it: > > include > > /* Purpose: to test how fclose() handles NULL pointers. > */ > > void main() { > int iStat; > FILE *fp; > char szLine[BUFSIZ]; > > fp = fopen("doesnotexist.file", "r"); > > if (!fp) { > iStat = fclose(fp); > } else { > fgets(szLine, BUFSIZ, fp); > iStat = fclose(fp); > } > } > Call me old fashioned but in all of my coding exploits if the file does not get opened then it should not be closed. Using your above example this is how I would have written it: #include /* Purpose: to test how fclose() handles NULL pointers. */ void main() { int iStat; FILE *fp; char fname[40] = "doesnotexist.file"; char szLine[BUFSIZ]; if (!(fp=fopen(fname,"r"))) { /* Could not open file send message then return. */ printf("Could not open the file %s!!.",fname); } else { fgets(szLine, BUFSIZ, fp); iStat = fclose(fp); } } In my opinion purposely trying to close a file that was not actually opened is like trying to clear or access memory that was not allocated in the first place. Just asking for trouble in my opinion. To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-questions" in the body of the message