Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize variable with cleanup attribute?

Tags:

c

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;
}
like image 402
2trill2spill Avatar asked Aug 14 '15 01:08

2trill2spill


1 Answers

Just mistypo. just...

//#define auto_clean __attribute__((cleanup (cleanup_buf)));
//                                                         ^
#define   auto_clean __attribute__((cleanup (cleanup_buf)))
like image 160
ikh Avatar answered Oct 05 '22 02:10

ikh