How does a c++ project using smart pointers like unique_ptr's know to free the resources when the program crashes?
Asked
Active
Viewed 202 times
1
-
1You want to lookup stack unwinding. And also define _crash_ more exactly. If the program aborts all memory will be to the OS anyways. – πάντα ῥεῖ Aug 24 '16 at 13:32
-
It depends on the "crash" - terminate will not unwind the stack, so destructors won't get called. There are some genral musing (about RAII) here: http://stackoverflow.com/questions/76796/general-guidelines-to-avoid-memory-leaks-in-c/77893#77893 – doctorlove Aug 24 '16 at 13:33
2 Answers
8
If the program crashes "gracefully" due to a handled exception, the stack unwinding will call the destructors on any smart pointers and free the memory.
For complete crashes (e.g. segmentation fault, call to std::terminate()
), it is the operating system that will free any memory and resources held by the program.

Karl Nicoll
- 16,090
- 3
- 51
- 65
1
When a C++ program crashes, it exits. The operating system cleans up any OS resources it may have asked for, which includes memory, but also other resources (file handles for example).
Thus, C++ does not clean up - the operating system does. What once was the C++ heap is returned to the operating system as free memory.

Lying Dog
- 1,484
- 2
- 12
- 19