27

I think that GCC extension __attribute__((cleanup)) is a good idea, at least for some cases, but i can't figure out how to use it in a good way. All i'm doing looks still really annoying.

I saw a lot of code doing #define _cleanup_(x) __attribute__((cleanup(x)) just to type less, but it there a way to pass there a standard function like free or closedir, fclose, etc?

As I see I can't just write:

__attribute__((cleanup(free))) char *foo = malloc(10);

Because the cleanup callback will receive char** pointer, and I have to always write something like:

static void free_char(char **ptr) { free(*ptr); }
__cleanup__((free_char)) char *foo = malloc(10);

That's pretty annoying, and the most annoying part is to define such cleanup functions for all types you need, because obviously you can't just define it for void **. What is the best way to avoid these things?

5
  • 7
    I think you've made a pretty good case for saying that __attribute__((cleanup)) is not a good idea. Jan 3, 2016 at 9:28
  • 11
    If you want destructors you know where to find them.
    – Ross Ridge
    Jan 3, 2016 at 9:33
  • 3
    @user3386109, i'd say it IS a good idea, but the realisation is a little bit broken. Or maybe there is something i don't understand, so that's why I'm asking. Jan 3, 2016 at 9:48
  • 2
    @coredump The realization is fine too. That the cleanup function expects a pointer to the variable makes sense, because the variable may not be a pointer itself but a large struct that is better not passed by value (cf. the difference between glib's g_autoptr and g_auto). Having two different attributes just for convenience would needlessly bloat the language extension.
    – dpi
    Jan 23, 2016 at 14:34
  • 2
    @RossRidge: better to have control over it than to worry about the baggage C++ brings to the table. So yes, if we want reasonable, good, non-hidden destructors, we know where to find them: C code under gcc and clang. May 19, 2021 at 15:47

2 Answers 2

20

You can't write __attribute__((cleanup(free))), but you don't need to write a free cleanup function for each type. It's ugly, but you can write this:

static void cleanup_free(void *p) {
  free(*(void**) p);
}

I first saw this in the systemd codebase.

For other functions you would in general need to a write a wrapper with an extra level of indirection for use with __attribute__((cleanup)). systemd defines a helper macro for this:

#define DEFINE_TRIVIAL_CLEANUP_FUNC(type, func)             \
    static inline void func##p(type *p) {                   \
            if (*p)                                         \
                    func(*p);                               \
    }                                                       \
    struct __useless_struct_to_allow_trailing_semicolon__

which is used all over the place, e.g.

DEFINE_TRIVIAL_CLEANUP_FUNC(FILE*, pclose);

#define _cleanup_pclose_ __attribute__((cleanup(pclosep)))
1
12

There's a library that builds general-purpose smart pointers (unique_ptr and shared_ptr) on top of __attribute__((cleanup)) here: https://github.com/Snaipe/libcsptr

It allows you to write higher-level code like this:

#include <stdio.h>
#include <csptr/smart_ptr.h>
#include <csptr/array.h>

void print_int(void *ptr, void *meta) {
    (void) meta;
    // ptr points to the current element
    // meta points to the array metadata (global to the array), if any.
    printf("%d\n", *(int*) ptr);
}

int main(void) {
    // Destructors for array types are run on every element of the
    // array before destruction.
    smart int *ints = unique_ptr(int[5], {5, 4, 3, 2, 1}, print_int);
    // ints == {5, 4, 3, 2, 1}

    // Smart arrays are length-aware
    for (size_t i = 0; i < array_length(ints); ++i) {
        ints[i] = i + 1;
    }
    // ints == {1, 2, 3, 4, 5}

    return 0;
}

As for idiomatic, though? Well the above is certainly close to idiomatic C++. Not C so much. The feature is clearly mainly supported in GCC and Clang because they have C++ compilers as well, so they have the option to make use of the RAII machinery in the C frontend at no extra cost; that doesn't make it a great idea to write C-intended-as-C this way. It kinda relies on a C++ compiler being present despite not actually being used.

If it were me, I'd probably investigate implementing autorelease pools, or something similar that can actually be done in pure C at the language level. Depends how quickly you need your resources to be freed; for memory, you usually can live without immediate cleanup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.