Last active
August 29, 2015 14:27
-
-
Save jeroen/cfd9fb55fa995d7b2eb5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Jeroen Ooms 2015 | |
* Example of queueing objects to be free later with their corresponding | |
* free() function. | |
*/ | |
#include <stdlib.h> | |
#include <stdio.h> | |
struct node { | |
void (*fun)(void *target); | |
void *ptr; | |
struct node *parent; | |
}; | |
struct node *head; | |
#define freemelater(...) freemelater_generic((void*) __VA_ARGS__) | |
void freemelater_generic(void *fun, void *ptr){ | |
struct node *x = malloc( sizeof(struct node) ); | |
x->parent = head; | |
x->fun = (void(*)(void*)) fun; | |
x->ptr = ptr; | |
head = x; | |
} | |
void gofreethings(){ | |
while(head != NULL){ | |
struct node *old = head; | |
head->fun(head->ptr); //free the target object | |
head = head->parent; | |
free(old); //free the node struct itself | |
printf("freeing something...\n"); | |
} | |
printf("clean up done.\n"); | |
} | |
int main(){ | |
/* alloc and queue cleanup */ | |
void *foo = malloc(1000); | |
freemelater(free, foo); | |
/* alloc and queue cleanup */ | |
int *bar = (int*) malloc(1000); | |
freemelater(free, bar); | |
/* alloc and queue cleanup */ | |
unsigned char *baz = malloc(1000); | |
freemelater(free, baz); | |
/* run cleanup */ | |
gofreethings(); | |
/* alloc and queue cleanup */ | |
void *test1 = malloc(1000); | |
freemelater(free, test1); | |
/* alloc and queue cleanup */ | |
int *test2 = (int*) malloc(1000); | |
freemelater(free, test2); | |
/* run cleanup */ | |
gofreethings(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment