Re:C: Simple Defer, Ready to Use
by kubb on Tuesday January 07, 2025 @01:13AM
(#42619817)
So, you recommend using goto, which indeed is the only available mechanism.
[ Parent
| on HN ]
> using goto, which indeed is the only available mechanism.
There are other options, but none of them is better, IMO. You can use nested functions:
char * p = malloc(10);
if(p!=0) {
doTheRealWork(p);
};
free(p);
In gcc, doTheRealWork can be a nested function or it you can force them to be inlined.You can also (more readable than that first alternative, IMO) wrap code in a single-iteration for or while loop and then use break to exit it:
char *p = null;
for(int i=0;i==0;i=1) {
p = malloc(10);
if(p==0) break;
…
}
free(p);
Both will get uglier if you need to free multiple resources, but will work.