2015-08-14 12 views
6

Gibt es eine Möglichkeit, eine Variable mit dem Compilerattribut cleanup zu initialisieren? Oder muss ich den Wert nach der Deklaration der Variablen festlegen?Wie initialisiert man Variable mit Cleanup-Attribut?

Ich habe versucht, das cleanup Attribut vor = malloc(10); wie im folgenden Beispiel und hinter = malloc(10); setzen, aber weder kompiliert.

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

Gibt es eine andere Syntax für cleanup Verwendung und Initialisierung der Variable in einer Zeile? Oder muss ich den Wert nach dem Deklarieren der Variablen wie im folgenden Beispiel einstellen?

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

Antwort

3

Nur mistypo. nur ...

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