On 20 March 2011 22:47, bd satish wrote: > Hi, > > I'm trying to close a file using fclose, but the following program seg-faults: > > > #include <stdio.h> > > int main(void) > { > FILE* fp = fopen("unfounded.txt", "r"); > > if(fp == NULL) > fclose(fp); > > return 0; > } > > > The file I'm trying to open doesn't exist in the directory, so fp is > indeed NULL. So it's just fclose(NULL). > Is fclose(NULL) legal according to the C standard ? As an end-user I > expect fclose(fp) to close the file (if it is already open) or just do > nothing (if it is not open). So the seg fault -- is this a compiler > bug ? > > PS: I hope this is the right place to ask this question.
It's not, this mailing list is for development of gcc, not help using it or help with C programming questions. Help using GCC can be sought on the gcc-h...@gcc.gnu.org mailing list but in this case you'd be better with a general C programming forum. Please take any follow up questions to a more suitable place, thanks. fclose() is provided by your system's C library, not the compiler, so it wouldn't be a compiler bug anyway. However fclose() requires a non-NULL pointer, so the problem is in your code. If the file pointer is null the file wasn't opened so there's nothing to close.