有没有办法用cleanup
编译器属性初始化变量?或者我必须在声明变量后设置值吗?
我已尝试将cleanup
属性放在= malloc(10);
前面,如下例和= malloc(10);
之后,但都没有编译。
#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;
}
使用cleanup
并在一行上初始化变量有不同的语法吗?或者我必须在声明变量之后设置值,如下例所示?
#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;
}
答案 0 :(得分:3)
只是迷雾。只是...
//#define auto_clean __attribute__((cleanup (cleanup_buf)));
// ^
#define auto_clean __attribute__((cleanup (cleanup_buf)))