Last active
August 14, 2025 17:42
-
-
Save jmatth11/f7f80bb1c378b77786ccf55bbe49fd80 to your computer and use it in GitHub Desktop.
Utilizing Compiler supported cleanup attribute as Defer in C.
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
| #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