What (can) happen if I use fclose () when fopen () fails

Here's my relatively simple scenario, and I'm wondering if I can save the conditional code myself and tidy it up. Its production code that someone wrote and I just clean it up. It didn't have fclose at all, so all I added was fclose () conditional 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 if(fp != null)

in my code? What are the implications of simple execution fclose(fp)

without validation? I read the C89 standard, but it was not clear to me what the results would be.

Greetings in advance

Steve

+3


source to share


2 answers


fclose

on a null pointer has undefined behavior. This means that it may crash or cause problems. I would stick with your checks as they are good practice and make the code easier to read.



+4


source


In BSD, there fclose( NULL )

will be a segfault. I believe the classic description of what can happen is that nasal demons can fly out of your nose, but I'm not sure if the behavior is undefined or unspecified. I never thought it was a very important difference: just don't do it.



+1


source







All Articles