Recently I came across a gcc extension that I have found rather useful: __attribute__(cleanup)
Basically, this allows you to assign a cleanup call to a local variable at the time it exits scope. For instance, given the following section of code, all memory must be maintained and handled explicitly in any and all cases within the call to foo
.
void foo() {
char * buff = ...; /* some memory allocation */
char * buff2 = 0, * buff3 = 0;
if (! buff) {
return;
} else {
buff2 = ...; /* memory allocation */
if (! buff2) {
goto clean_exit;
} else {
/* ... and so on ... */
}
}
clean_exit:
free (buff);
free (buff2);
free (buff3);
}
However, by using the extension that can reduce to
#define clean_pchar_scope __attribute__((cleanup(pchar_free)))
void pchar_free (char ** c) { free (*c); }
void foo () {
char * buff clean_pchar_scope = ...; /* some memory allocation */
char * buff2 clean_pchar_scope = 0, * buff3 clean_pchar_scope = 0;
if (! buff)
return;
buff2 = ...; /* memory allocation */
if (! buff2)
return;
/* and so on */
}
Now all memory is reclaimed on the basis of scope without the use of nested if/else or goto constructs coupled with a consolidated memory release section of the function. I realize that the use of goto could be avoided there for a more nested if/else construct (so, please, no holy wars on the goto...) and that the example is contrived, but the fact remains that this is can be quite a useful feature.
Unfortunately, as far as I know, this is gcc-specific. I'm interested in any portable ways to do the same thing (if they even exist). Has anyone had experiences in doing this with something other than gcc?
EDIT: Seems that portability is not in play. Considering that, is there a way to do this outside of the gcc space? It seems like to nice a feature to be gcc-specific...
defer
statement that does what you want! Here (gustedt.wordpress.com/2020/12/14/a-defer-mechanism-for-c) is a blogpost that summarizes the paper – Zoba