如何用cleanup属性初始化变量?

有没有办法用cleanup编译器属性初始化变量? 或者我必须在声明变量后设置值?

我已经尝试将cleanup属性放在= malloc(10);前面= malloc(10); 比如下面的示例和后面= malloc(10); 但是没有编译。

 #include  #include  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; } 

在一行上使用cleanup和初始化变量有不同的语法吗? 或者我必须在声明变量后设置值,如下例所示?

 #include  #include  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; } 

只是迷雾。 只是…

 //#define auto_clean __attribute__((cleanup (cleanup_buf))); // ^ #define auto_clean __attribute__((cleanup (cleanup_buf)))