Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to atexit()

Tags:

c

On my program I am using a static variable (there is no way to do otherwise), and the problem is it needs to be free'd at exit.

How would I be able to achieve this without having to declare this variable as global ?

I was thinking of atexit function, but it doesn't seem to be able to take an argument. Isn't there any trick to pass my variable ?

Thanks.

like image 918
Ra'Jiska Avatar asked Oct 27 '25 04:10

Ra'Jiska


1 Answers

Not sure if it meets your requirements, but I would make the static variable a file-scope static, off in one source file, something like this:

static char *my_static_variable = NULL;

static void my_cleanup_function()
{
    free(my_static_variable);
}

void my_initialization_function()
{
    my_static_variable = malloc(10);
    atexit(my_cleanup_function);
}

That is, my_static_variable and my_cleanup_function are visible only in that one source file; they are not program-wide globals.

As a side note, though, it is not typically necessary to free malloc'ed memory on exit. Anything you allocate will, in effect, be automatically freed for you, by the operating system, when it releases the memory which had been used by your process.

like image 188
Steve Summit Avatar answered Oct 29 '25 18:10

Steve Summit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!