Skip to content

Instantly share code, notes, and snippets.

@aedrax
Forked from baruch/defer.h
Last active September 8, 2022 23:06
Show Gist options
  • Save aedrax/e59ed8f507feeb5d18cc2847e493a39f to your computer and use it in GitHub Desktop.
Save aedrax/e59ed8f507feeb5d18cc2847e493a39f to your computer and use it in GitHub Desktop.
Defer cleanup for C (gcc and llvm)
#define DEFER_MERGE(a, b) a##b
#define DEFER_VARNAME(a) DEFER_MERGE(defer_scopevar_, a)
#define DEFER_FUNCNAME(a) DEFER_MERGE(defer_scopefunc_, a)
#define DEFER(BLOCK) \
void DEFER_FUNCNAME(__LINE__)(__attribute__((unused)) int *a) { BLOCK; } \
__attribute__((cleanup(DEFER_FUNCNAME(__LINE__)))) int DEFER_VARNAME(__LINE__)
// Usage:
/*
void dosomething()
{
char* data = malloc(100);
DEFER(free(data));
dosomethingwith(data);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment