How to use atexit

I need to use "atexit" to cleanly terminate the execution of a program in case it is aborted. My program has to run a function called "release_allocator()" at any time it finishes, whether it terminates normally or not. Am I doing it correctly?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void AtExitFunc()
{
    release_allocator();
}


int main(int argc, char ** argv) {
	
    // Set default values.
    int intMemSize = 512;
    int intBasicBlock = 128;

    atexit(AtExitFunc);
    init_allocator(intBasicBlock, intMemSize);
    ackerman_main();
    release_allocator();

    return 0;
}

Last edited on
I am afraid that atexit is not the right function for you. I am not sure if there are any functions that are called when a program terminates abnormally. Maybe some of the experts here can recommend sth. to you.
The function pointed by func is automatically called without arguments when the program terminates normally.

http://www.cplusplus.com/reference/cstdlib/atexit/
What does the "aborted" mean?
I used "aborted" to describe when the user "interrupts" execution of the program by pressing a key or a combination of keys in case it is taking too long.
"A key" as in "Ctrl-C" to send a SIGINT?
https://en.wikipedia.org/wiki/C_signal_handling
https://en.wikipedia.org/wiki/Unix_signal

Or

"A key" as in "the program has a loop that occasionally handles input"?


If something takes long, it most likely has a loop. A loop can check the state of a flag and break; in controlled fashion. A signal-handler can set such flag.

Presumably.
A key as in "CTRL-C."

My program might take long to execute depending on certain circumstances. That is why I can interrupt execution to test with different values.
The atexit() will not help in the case of ctrl-C, since atexit() is only called on normal program termination and ctrl-C isn't considered normal program termination.

If you want to trap ctrl-C you need to use the appropriate single catch mechanisms.

Signal handling might be what you look for:
https://www.tutorialspoint.com/cplusplus/cpp_signal_handling.htm
Topic archived. No new replies allowed.