Should we use exit() in C?

前端 未结 7 1143
醉梦人生
醉梦人生 2020-12-02 16:44

There is question about using exit in C++. The answer discusses that it is not good idea mainly because of RAII, e.g., if exit is called somewhere

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 17:02

    Rather than abort(), the exit() function in C is considered to be a "graceful" exit.

    From C11 (N1570) 7.22.4.4/p2 The exit function (emphasis mine):

    The exit function causes normal program termination to occur.

    The Standard also says in 7.22.4.4/p4 that:

    Next, all open streams with unwritten buffered data are flushed, all open streams are closed, and all files created by the tmpfile function are removed.

    It is also worth looking at 7.21.3/p5 Files:

    If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination. Other paths to program termination, such as calling the abort function, need not close all files properly.

    However, as mentioned in comments below you can't assume that it will cover every other resource, so you may need to resort to atexit() and define callbacks for their release individually. In fact it is exactly what atexit() is intended to do, as it says in 7.22.4.2/p2 The atexit function:

    The atexit function registers the function pointed to by func, to be called without arguments at normal program termination.

    Notably, the C standard does not say precisely what should happen to objects of allocated storage duration (i.e. malloc()), thus requiring you be aware of how it is done on particular implementation. For modern, host-oriented OS it is likely that the system will take care of it, but still you might want to handle this by yourself in order to silence memory debuggers such as Valgrind.

提交回复
热议问题