Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 07 Jun 1999 00:37:40 -0700 (PDT)
From:      Shawn Workman <malpert@holdenz.com>
To:        freebsd-questions@freebsd.org
Subject:   RE: Possible C library bug?
Message-ID:  <XFMail.990607003603.malpert@holdenz.com>
In-Reply-To: <Pine.NEB.4.10.9906062301420.99176-100000@ds9.dreamhaven.net>

next in thread | previous in thread | raw e-mail | index | archive | help

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 <stdio.h>
> 
> /* 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 <stdio.h>
 
 /* 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




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?XFMail.990607003603.malpert>