3 ms·
I'm not familiar with using attributes for cleanup, but isn't the problem caused by the predeclaration of the variables? That is, wouldn't this work (and be sh
by nkurz 11y ago
I'm not familiar with using attributes for cleanup, but isn't the problem caused by the predeclaration of the variables? That is, wouldn't this work (and be shorter and simpler)?
int f (void) {
_cleanup_free char *s1 = strdup ("foo");
if (!s1) return -1;
_cleanup_free char *s2 = strdup ("bar");
if (!s2) return -1;
// ...
return 0;
}
- nkurz 11y agoOK, 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)