There is GCC-specific attribute cleanup
. It might be used like this:
#define SCOPED_FILE __attribute__((cleanup(cleanup_file)))
void
cleanup_file(FILE **file) {
if (*file != NULL) { fclose(*file); }
}
…
FILE *SCOPED_FILE file = fopen(…); // file will be closed at the end of scope.
I thought it would be handy to have cleanup function for any malloc
ed memory. Having to circumvent casting issues, I came up with the following implementation:
#define SCOPED_MEM __attribute__((cleanup(cleanup_mem)))
static inline void
cleanup_mem(void *pmem) {
void *mem = *(void **)pmem;
free(mem);
}
int main(void) {
char *SCOPED_MEM str = malloc(20);
strcpy(str, "pineapple");
printf("hi, %s\n", str);
// str will be free'd at the end of scope
}
It does work, but smells funny, because I don't directly specify void **
as parameter type, but rather cast to it.
I wonder, if there are some problems with it that I don't see right now.