Skip to content

Instantly share code, notes, and snippets.

@dgalling
Created November 7, 2014 19:44
Show Gist options
  • Save dgalling/a2dfe5d914aa0c027b2a to your computer and use it in GitHub Desktop.
Save dgalling/a2dfe5d914aa0c027b2a to your computer and use it in GitHub Desktop.
Deferred free in C
typedef struct free_list_t {
void (*func)(void *);
void *arg;
struct free_list_t *next;
} FreeList;
void _defer(FreeList **f, void (*func)(void *), void *arg) {
if (arg == NULL) {
return;
}
FreeList *new = calloc(1, sizeof(FreeList));
new->func = func;
new->arg = arg;
new->next = *f;
*f = new;
}
#define DEFER(F, FUNC, ARG) _defer(&(F), (void (*)(void *))&(FUNC), (void *)ARG);
void defer_free(FreeList *f) {
while (f != NULL) {
FreeList *temp = f->next;
f->func(f->arg);
free(f);
f = temp;
}
}
#define RETURN(f, code) defer_free((f)); return (code);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment