jeudi 13 août 2015

How to intialize variable with cleanup attribute?

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire