A good and idiomatic way to use GCC and clang __attribute__((cleanup)) and pointer declarations
<p>I think that GCC extension <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html" rel="noreferrer"><code>__attribute__((cleanup))</code></a> 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.</p>

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

<p>As I see I can't just write:</p>

<pre><code>__attribute__((cleanup(free))) char *foo = malloc(10);
</code></pre>

<p>Because the cleanup callback will receive <code>char**</code> pointer, and I have to always write something like:</p>

<pre><code>static void free_char(char **ptr) { free(*ptr); }
__cleanup__((free_char)) char *foo = malloc(10);
</code></pre>

<p>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 <code>void **</code>. What is the best way to avoid these things?</p>