Skip to content

Instantly share code, notes, and snippets.

@jmatth11
Last active August 14, 2025 17:42
Show Gist options
  • Select an option

  • Save jmatth11/f7f80bb1c378b77786ccf55bbe49fd80 to your computer and use it in GitHub Desktop.

Select an option

Save jmatth11/f7f80bb1c378b77786ccf55bbe49fd80 to your computer and use it in GitHub Desktop.
Utilizing Compiler supported cleanup attribute as Defer in C.
#include <stdio.h>
#include <string.h>
#define DEFER(func) __attribute__((__cleanup__(func)))
static void free_char(char **p) {
if (p == NULL) return;
if (*p == NULL) return;
free(*p);
*p = NULL;
}
int main(void) {
DEFER(free_char) char *test = malloc((sizeof(char)*14));
strncpy(test, "Hello, World!", 13);
test[14] = '\0';
printf("test string = \"%s\"\n", test);
// free_char is called when this function exits
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment