Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass in different function pointers into atexit in c?

I understand that atexit() takes in a function pointer of this type void (*function)(void). What I want to do is that whenever the porgam exists it runs a function to free of all the memory. So I want atexit() to take in this function pointer instead
void (*function)(struct Node). Is there a way around this, or something similar that will allow me to do this.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could add your own register for cleanup functions:

typedef void atexit_f(void*);
void my_atexit(atexit_f* callback, void *data);

The register would be kept in a global variable (i.e. linked list).
The register would be cleaned up in a cleanup function registered with atexit().

struct cleanup_node {
   atexit_f *cb;
   void *data;
   struct cleanup_node *next;
};

static struct cleanup_node *head;

void my_atexit_cleanup(void) {
  for (struct cleanup_node *node = head; node; node = node->next) {
     node->cb(node->data);
  }
  // free nodes itself
}

...

int main() {
  atexit(my_atexit_cleanup);
  ...
  my_atexit(some_function, some_data);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading