Skip to content

Instantly share code, notes, and snippets.

@davepacheco
Forked from gcmurphy/goto.c
Last active December 11, 2015 02:39
Show Gist options
  • Save davepacheco/4531797 to your computer and use it in GitHub Desktop.
Save davepacheco/4531797 to your computer and use it in GitHub Desktop.
void example()
{
A *a;
B *b = NULL;
a = a_new();
if (! a){
goto end;
}
b = b_new(a);
if (! b){
goto end;
}
use_b(b);
end:
b_delete(b);
a_delete(a);
puts("bye");
}
void example()
{
A *a;
B *b = NULL;
if ((a = a_new()) == NULL ||
(b = b_new()) == NULL) {
a_delete(a);
goto end;
}
use_b(b);
b_delete(b);
a_delete(a);
end:
puts("bye");
}
@davepacheco
Copy link
Author

The second example uses the same fact, plus short-circuiting. It's much more concise.

@seliopou
Copy link

Isn't that first a_delete(a) superfluous? It'll cause a double-free on a if b_new() fails.

@davepacheco
Copy link
Author

@seliopou My second example was busted. I just fixed it.

@seliopou
Copy link

@davepacheco 👍 That makes a lot more sense.

@gcmurphy
Copy link

Thanks for taking the time to write a more concise / realistic example. I'll incorporate this into the blog post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment