From 80eb05876f302ef713556637a54bf82c00506139 Mon Sep 17 00:00:00 2001 From: Dimitri Staessens Date: Wed, 16 Oct 2019 20:15:56 +0200 Subject: lib: Clean up fail path in constructors The node construction path is revised using gotos to avoid repetition. Signed-off-by: Dimitri Staessens Signed-off-by: Sander Vrijders --- src/lib/btree.c | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/lib/btree.c b/src/lib/btree.c index 0b5a80d0..c8c71bfd 100644 --- a/src/lib/btree.c +++ b/src/lib/btree.c @@ -83,22 +83,17 @@ static struct btnode * btnode_create(size_t k) node = malloc(sizeof(*node)); if (node == NULL) - return NULL; + goto fail_node; assert(k > 0); node->keyvals = malloc(sizeof(*node->keyvals) * k); - if (node->keyvals == NULL) { - free(node); - return NULL; - } + if (node->keyvals == NULL) + goto fail_keyvals; node->children = malloc(sizeof(*node->children) * (k + 1)); - if (node->children == NULL) { - free(node->keyvals); - free(node); - return NULL; - } + if (node->children == NULL) + goto fail_children; for (i = 0; i < k; ++i) { node->children[i] = NULL; @@ -111,6 +106,13 @@ static struct btnode * btnode_create(size_t k) node->leaf = true; return node; + + fail_children: + free(node->keyvals); + fail_keyvals: + free(node); + fail_node: + return NULL; } static void btnode_destroy(struct btnode * node) @@ -366,14 +368,14 @@ static int btnode_delete(struct btnode * node, struct btree * btree_create(size_t k) { - struct btree * tree = malloc(sizeof(*tree)); - if (tree == NULL) + struct btree * tree; + + if (k < 1 || k > BTREE_MAX_ORDER) return NULL; - if (k < 1 || k > BTREE_MAX_ORDER) { - free(tree); + tree = malloc(sizeof(*tree)); + if (tree == NULL) return NULL; - } tree->k = k; tree->root = NULL; -- cgit v1.2.3