-
-
Save davepacheco/4531797 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
The second example uses the same fact, plus short-circuiting. It's much more concise.
Isn't that first a_delete(a)
superfluous? It'll cause a double-free on a
if b_new()
fails.
@seliopou My second example was busted. I just fixed it.
@davepacheco 👍 That makes a lot more sense.
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
There's a reason free() accepts NULL, and why higher-level versions (e.g., a_free()) should also accept NULL. The first example uses this with goto and is much clearer.