Why glibc's fclose(NULL) cause segmentation fault instead of returning error?

后端 未结 5 795
天命终不由人
天命终不由人 2020-12-03 05:02

According to man page fclose(3):

RETURN VALUE

Upon successful completion 0 is returned. Otherwise, EOF is return

5条回答
  •  Happy的楠姐
    2020-12-03 05:29

    fclose(NULL) should succeed. free(NULL) succeeds, because that makes it easier to write cleanup code.

    Regrettably, that's not how it was defined. Therefore you can't use fclose(NULL) in portable programs. (E.g. see http://pubs.opengroup.org/onlinepubs/9699919799/).

    As others have mentioned, you don't generally want an error return if you pass NULL to the wrong place. You want a warning message, at least on debug/test builds. Dereferencing NULL gives you an immediate warning message, and the opportunity to collect a backtrace which identifies the programming error :). While you're programming, a segfault is about the best error you can get. C has many more subtle errors, which take much longer to debug...

    It is possible to abuse error returns to increase robustness against programming errors. However, if you're worried a software crash would lose data, note that exactly the same can happen e.g. if your hardware loses power. That's why we have autosave (since Unix text editors with two-letter names like ex and vi). It'd still be preferable for your software to crash visibly, rather than continuing with an inconsistent state.

提交回复
热议问题