如何初始化与清理属性变量? [英] How to initialize variable with cleanup attribute?

查看:168
本文介绍了如何初始化与清理属性变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来初始化与清除编译器属性的变量?还是我必须声明变量后设置的值?

我试过把清除 =的malloc(10)前面的属性; 比如上例中下面和后面 =的malloc(10); 但既不编译。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;静态内嵌无效cleanup_buf(字符** BUF)
{
    如果(* BUF == NULL)
    {
        返回;
    }    输出(清理\\ n);    免费(* BUF);
}#定义auto_clean __attribute __((清理(cleanup_buf)));INT主要(无效)
{
    字符* BUF auto_clean =的malloc(10);
    如果(BUF == NULL)
    {
        的printf(malloc的\\ n);
        返回-1;
    }    返回0;
}

有没有使用清除并在同一行初始化变量不同的语法?还是我声明变量就像下面的例子后,所设置的值?

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;静态内嵌无效cleanup_buf(字符** BUF)
{
    如果(* BUF == NULL)
    {
        返回;
    }    输出(清理\\ n);    免费(* BUF);
}/ *请使用我们要自动清理变量此属性。 * /
#定义auto_clean __attribute __((清理(cleanup_buf)));INT主要(无效)
{
    字符* BUF auto_clean;    BUF = malloc的(10);
    如果(BUF == NULL)
    {
        的printf(malloc的\\ n);
        返回-1;
    }    返回0;
}


解决方案

只是mistypo。只是......

  //#定义auto_clean __attribute __((清理(cleanup_buf)));
// ^
#定义auto_clean __attribute __((清理(cleanup_buf)))

Is there a way to initialize a variable with the cleanup compiler attribute? or do I have to set the value after declaring the variable?

I've tried putting the cleanup attribute in front of = malloc(10); like in the example below and behind = malloc(10); but neither compiles.

#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 a different syntax for using cleanup and initializing the variable on one line? Or do I have to set the value after declaring the variable like 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;
}

解决方案

Just mistypo. just...

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

这篇关于如何初始化与清理属性变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆