by brown9-2 · 15y ago · 0 comments
So rather than this:
void test()
{
int *x = malloc(1000);
int *y = malloc(1000);
for(int i = 0; i < 999; i++) {
if(badThing) {
free(x);
free(y);
return;
}
doStuff()
if(otherBadThing) {
free(x);
free(y);
return;
}
}
free(x);
free(y);
return;
}
You'd have: void test()
{
int *x = malloc(1000);
int *y = malloc(1000);
for(int i = 0; i < 999; i++) {
if(badThing)
goto ret;
doStuff()
if(otherBadThing)
goto ret;
}
ret:
free(x);
free(y);
return;
} void do_stuff(char *name) {
char *my_name = strdup(name);
if (condition_signalling_no_work()) goto done;
if (do_something_with(my_name)) goto done;
...
done:
free(my_name);
return;
}
If it helps think of it as a finally block. The function does some things and no matter what it has to run that block at the end.The way it is used in that code is pretty horrible, IMO, and splitting it into functions and using "return" in place of goto would have been far better.