37

Possible Duplicate:
Will exit() or an exception prevent an end-of-scope destructor from being called?

In C++, when the application calls exit(3) are the destructors on the stack supposed to be run to unwind the stack?

Community
  • 1
  • 1
WilliamKF
  • 41,123
  • 68
  • 193
  • 295
  • And, is there an alternative approach? `throw` a special type instead of calling `exit`, catch it in `main`, and then `return` from `main` instead of `exit` from `main`? – Aaron McDaid Jun 11 '16 at 18:10
  • 1
    @AaronMcDaid I don't understand your question. Alternative approach to what? What would you be trying to accomplish by avoiding a call to `exit()`? In one of my apps, I do throw an `customExit` object and catch it in main and use an integer value from the `customExit` object to supply the return value from main, this way my RAII destructors are run to clean up things like temporary files. – WilliamKF Jun 11 '16 at 19:06
  • your comment answered my (badly written) question exactly. Thanks! Basically, I wanted confirmation that other people use this `throw` approach to ensure everything is destructed in a normal program exit – Aaron McDaid Jun 11 '16 at 20:10

2 Answers2

52

No, most destructors are not run on exit().

C++98 §18.3/8 discusses this.

Essentially, when exit is called static objects are destroyed, atexit handlers are executed, open C streams are flushed and closed, and files created by tmpfile are removed. Local automatic objects are not destroyed. I.e., no stack unwinding.

Calling abort lets even less happen: no cleanup whatsoever.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
  • 1
    For people who want no cleanup to happen, _exit() might be a better call than abort(), since abort will raise the SIGABRT signal, typically resulting in behavior quite similar to a crash. – Jeremy Friesner Nov 01 '16 at 05:45
10

If your OS is reasonable (Unix, Linux, or a recent Windows), calling exit() tells the kernel to de-allocate all the processes' memory. The stack doesn't need to be unwound; it will simply cease to exist.

Barry Brown
  • 20,233
  • 15
  • 69
  • 105
  • 27
    And any RAII code in stack destructors will NOT be called. Which may not matter if it deals only with memory private to the process; but which matters if it deals with (a) files that need to be deleted or renamed,or otherwise cleaned up, and (b) the integrity of data structures shared between processes in shared memory. // For reasons such as these, some projects have forbidden the use of exit, and/or have redefined exit() to throw an exception that will cause stack unwinding. – Krazy Glew Jul 13 '12 at 02:13