I am developing a project in C, and I need to free the allocated memory and also close all the open files before it exits.
I decided to implement a clean
function that will do all this stuff and call it with atexit
because there are a lot of possible exit scenarios.
The problem is that atexit
doesn't allow me to set functions with parameters, so I can't send to clean
the pointers that need to be freed in the end of the process.
So I need to declare as global variables every pointer that may need to be freed, and every file that may remaining open in the program? (I already did that but doesn't looks good) or does exist a similar function to atexit
that allows to send parameters? or more probably there is another way that I am missing?
Using a static pointer inside a function:
Another method using a single global variable: you can store all objects to be freed in an array of pointers or a linked list, this example uses
realloc
(doesn't check (m/re)alloc for brevity):There is no way to pass any parameters to
atexit()
, so you're stuck using global variables.When your program terminates normally, through
exit()
or by returning frommain()
, it will automatically flush and close any open streams and (under most operating systems) free allocated memory. However, it is good practice to explicitly clean up your resources before the program terminates, because it typically leads to a more structured program. Sometimes the cleanest way to write your program is to just exit and leave the cleanup to the implementation.But be warned that you should always check the return value of
fclose()
. See "What are the reasons to check for error on close()?" for an anecdote about what could happen when you don't.