3 ms·
OK, I tested it. Yes, this approach worked fine for me in GCC, Clang, and ICC. #include <stdlib.h> #include <stdio.h> #include <string.h> #define aut
by nkurz 11y ago
OK, I tested it. Yes, this approach worked fine for me in GCC, Clang, and ICC.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define autofree __attribute((cleanup(autofree_func)))
#define PASS 0
#define FAIL 1
void autofree_func(void *ptr_ptr) {
void *ptr = * (void **) ptr_ptr;
printf("%s(%p)\n", __func__, ptr);
free(ptr);
}
int test(int fail1, int fail2) {
printf("\n%s(%s, %s):\n", __func__,
fail1 ? "FAIL" : "PASS",
fail2 ? "FAIL" : "PASS");
autofree char *s1 = strdup("foo");
if (fail1) return -1;
printf("s1: '%s' (%p)\n", s1, s1);
autofree char *s2 = strdup("bar");
if (fail2) return -1;
printf("s2: '%s' (%p)\n", s2, s2);
return 0;
}
int main(/* int argc, char **argv */) {
test(PASS, PASS);
test(PASS, FAIL);
test(FAIL, FAIL);
return 0;
}
nate@skylake$ cc -Wall -Wextra -Wconversion -O3 scoping.c -o scoping
nate@skylake$ ./scoping
test(PASS, PASS):
s1: 'foo' (0x2056010)
s2: 'bar' (0x2056030)
autofree_func(0x2056030)
autofree_func(0x2056010)
test(PASS, FAIL):
s1: 'foo' (0x2056010)
autofree_func(0x2056030)
autofree_func(0x2056010)
test(FAIL, FAIL):
autofree_func(0x2056010)