A useful function to know- atexit

Warning signs
Image by Annalise Batista from Pixabay

This is in C, but applies to C++ as well and is part of stdlib. Perhaps you’ve written a program and when it exits, you want it run some final code. The typical use case for this is releasing resources such as memory allocations and closing files. If you are doing networking then it might also be closing network handles.

Then you need atexit(). You pass in the name of void function. When it finishes, it jumps to that function and runs it. Here’s some code to show it in use.

void ExitFunction(void) {
    printf("Exited");
}    

int atv = atexit(ExitFunction);

As good programming practice, you should check that value to make sure it’s 0. If it isn’t then your exit handler failed to register. I’m not sure what would cause that (overzealous antivirus software?)

You might notice that the ExitFunction has a (void) parameter rather than (). The two are the same but atexit() has been told to expect void parameters and will be disappointed should you fail to comply. Not disappointed enough to give you an error but you will incur a warning and you know how I hate to see those.

The reason why I hate warnings is that not all warnings are equal. This one is trivial and could be ignored, but others aren’t and really need dealing with. So I go for zero tolerance to warnings. Some compilers like gcc have a setting to tell the compiler to treat all warnings as errors.

Leave a Reply

Your email address will not be published. Required fields are marked *