Re: SIGSEGV on fclose.

From: Rogier Wolff (R.E.Wolff@BitWizard.nl)
Date: Thu Jul 13 2000 - 13:44:06 EST


David Woodhouse wrote:
>
> matt@theBachChoir.org.uk said:
> > but his example fcloses a file which was not opened. This isn't
> > "further access".
>
> He said that it arises from a program that closes a file twice.
>
> > Is it difficult for Linux to spot the the file isn't open and return
> > EBADF? What does POSIX have to say about this? IMHO making it easier
> > to port your programs to Linux (and behaving a little more sanely :)
> > is worth a couple of extra bytes of anyone's kernel.
>
> If it got as far as the kernel, it'd get EFAULT rather than SIGSEGV. It's a
> glibc issue if anything.

Guys,

Note that he's fclosing a FILE* and not doing "close" on a file
descriptor.

fopen needs to malloc an area that has is of type "FILE", and it
returns the pointer to that. fclose needs to free () that area. Right?
(If you don't a program that happens to fopen/fclose millions of files
runs out of memory in the end).

free-ing an area twice is BAD. REALLY BAD. (Excuse my shouting).

The problem is that you can't know if say "printf" has been called by
a signal handler and that may have allocated some memory, stomping
over whatever was stored there. So, the best thing to do when users
free a pointer twice is to just segfault: This leads to the problems
getting fixed. This prevents hard-to-find bugs years later when nobody
knows any more what the code was supposed to do.

You should:

#define my_fclose(fp) do { \
        if (fp) fclose (fp); \
        fp = NULL; \
        } while (0)

or if you really want:

void my_fclose (FILE *fp)
{
  fclose (fp);
}

#define fclose(fp) do { \
        if (fp) my_fclose (fp); \
        fp = NULL; \
        } while (0)

which would mean you don't have to modify all calls to "fclose" in the
main source files.

Don't see this as "It doesn't work on Linux, but it does on all other
Unices", but as: "Linux thankfully helped me find a serious bug that
had gone unnoticed for a long time".

                                Roger.

-- 
** R.E.Wolff@BitWizard.nl ** http://www.BitWizard.nl/ ** +31-15-2137555 **
*-- BitWizard writes Linux device drivers for any device you may have! --*
*       Common sense is the collection of                                *
******  prejudices acquired by age eighteen.   -- Albert Einstein ********

- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to majordomo@vger.rutgers.edu Please read the FAQ at http://www.tux.org/lkml/



This archive was generated by hypermail 2b29 : Sat Jul 15 2000 - 21:00:17 EST