fclose
on a null pointer has undefined behaviour. This means it could segfault or cause you problems. I would stick with your checks as they are good practise and make the code easier to read.
What (might) happen if I use fclose() when fopen() failed [closed]
Question
Here is my relatively simple scenario, and I'm wondering if I can save myself a conditional and tidy the code up a bit. Its production code that someone else wrote and I'm just tidying up. It had no fclose at all, so all I have added is the conditional fclose() lines:
FILE *fp;
struct stat sb;
/* snipped code */
if (((fp = fopen (config_file, "r+")) == NULL) || (fstat (fileno (fp), &sb))) {
syslog (LOG_ERR, "Fault. Unable to read config file");
if (fp != NULL) {
fclose (fp);
}
return -1;
}
/* code carries on after this */
The question is, do I really need to have the if(fp != null)
in my code? What are the implications of just doing an fclose(fp)
without checking? I had a read of the C89 standard but it wasn't clear to me from that what the results would be.
Cheers in advance
Steve
Solution
OTHER TIPS
In BSD, fclose( NULL )
will segfault. I believe that the classic description of what may happen is that nasal demons may fly out of your nose, but am uncertain if the behavior is undefined or unspecified. I've never considered it a terribly important distinction: just don't do it.