Is there a way to initialize a variable with the cleanup attribute of the compiler? or do I need to set a value after declaring a variable?
I tried putting the cleanup attribute before = malloc(10); as in the example below and below = malloc(10); but does not compile.
#include <stdio.h> #include <stdlib.h> static inline void cleanup_buf(char **buf) { if(*buf == NULL) { return; } printf("Cleaning up\n"); free(*buf); } #define auto_clean __attribute__((cleanup (cleanup_buf))); int main(void) { char *buf auto_clean = malloc(10); if(buf == NULL) { printf("malloc\n"); return -1; } return 0; }
Is there another syntax for using cleanup and initializing a variable on one line? Or do I need to set a value after declaring a variable, as in the example below?
#include <stdio.h> #include <stdlib.h> static inline void cleanup_buf(char **buf) { if(*buf == NULL) { return; } printf("Cleaning up\n"); free(*buf); } /* Use this attribute for variables that we want to automatically cleanup. */ #define auto_clean __attribute__((cleanup (cleanup_buf))); int main(void) { char *buf auto_clean; buf = malloc(10); if(buf == NULL) { printf("malloc\n"); return -1; } return 0; }
source share