https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98313

            Bug ID: 98313
           Summary: Allow __attribute__((cleanup)) in types
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: david at westcontrol dot com
  Target Milestone: ---

The gcc __attribute__((cleanup)) feature can be useful for making the
equivalent of a C++ destructor in C code, as a way of ensuring resources are
freed even if you exit a function early with return.  Typical use-cases are
malloc'ed memory and locks.

In many situations, attaching the cleanup attribute to a type would give neater
code with fewer chances of error.  For example:

void indirect_free(void ** p)  {
    free(*p);
    *p = 0;
}

extern void do_something(int * p);

void foo(void) {
    void * p = malloc(16);
    do_something(p);
    free(p);
}

void foo2(void) {
    __attribute__((cleanup(indirect_free)))
    void * p = malloc(16);
    do_something(p);
}

Here, the cleanup attribute in "foo2" means you don't have to remember to free
p after calling do_something() - and if the function has multiple allocations,
this results in neater code with lower risk of bugs than a "traditional"
goto-based error handling.  But you still have to remember to put the cleanup
attribute on each relevant pointer.

If instead you had:

typedef __attribute__((cleanup(indirect_free))) void* auto_voidp;

auto_voidp auto_malloc(size_t size) {
    return malloc(size);
}


then your code could be:

void foo3(void) {
    void * p = auto_malloc(16);
    do_something(p);
}


It would not remove all possibilities of error - copying an auto_voidp here
could easily lead to double-free errors.  (But this is C, not C++ - we need to
leave /some/ fun for the people debugging the code...)


Basically, all I'd like here is that if you attach a cleanup attribute to a
type (struct, typedef, etc.), then the attribute is automatically applied to
any definitions of variables of that type.

Reply via email to