In C++ if I wish to have code called upon something bad happening I can place the code in the destructor, or a try-catch.
Is there a similar technique in C, whereby if the program terminates unexpectedly I can call a particular routine (to clean-up resources)?
In C, you use the C standard library function atexit
, which allows you to specify a void
function taking no parameters to be called when the program terminates (conceptually, when the closing brace }
of the first calling of main
is reached).
You can register up to 32 such functions in portable C and they are called in the reverse order in which they were registered.
See http://en.cppreference.com/w/c/program/atexit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With