Skip to content

Instantly share code, notes, and snippets.

@singalen
Created November 11, 2016 22:13
Show Gist options
  • Save singalen/4321e0cc7acaddcb9673d6d509b456ec to your computer and use it in GitHub Desktop.
Save singalen/4321e0cc7acaddcb9673d6d509b456ec to your computer and use it in GitHub Desktop.
A stepwise resource allocation in C. Example for http://softwareengineering.stackexchange.com/questions/335851/
int f() {
FILE *fp = NULL;
Forest* forest = NULL;
Tree *tree = NULL;
Element *element = NULL;
int status = 0;
fp = fopen("data.txt", "rb");
forest = generate_forest(fp, ...);
if (!forest) {
status = 1;
goto exit;
}
tree = get_tree(forest, "SPAIN"...);
if (!tree) {
status = 1;
goto exit;
}
element = malloc(sizeof(element));
if (!element) {
status = 1;
goto exit;
}
element->value = MAGIC;
if (tree_add(tree, element) != 0) goto exit;
// ...
exit:
if (status != 0)
global_logger.error("There's a problem in the forest!");
if (element)
free (element);
if (forest)
release_forest (forest);
if (fp)
fclose (fp);
return status;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment