Mon, 18 May 2015 18:39:19 +0200
added free() to AVL tree implementation + use UcxAllocator
ucx/avl.c | file | annotate | diff | comparison | revisions | |
ucx/avl.h | file | annotate | diff | comparison | revisions |
--- a/ucx/avl.c Mon May 18 12:54:18 2015 +0200 +++ b/ucx/avl.c Mon May 18 18:39:19 2015 +0200 @@ -107,7 +107,7 @@ } UcxAVLTree *ucx_avl_new_a(cmp_func cmpfunc, UcxAllocator *allocator) { - UcxAVLTree *tree = malloc(sizeof(UcxAVLTree)); + UcxAVLTree *tree = almalloc(allocator, sizeof(UcxAVLTree)); if (tree) { tree->allocator = allocator; tree->cmpfunc = cmpfunc; @@ -118,6 +118,20 @@ return tree; } +static void ucx_avl_free_node(UcxAllocator *al, UcxAVLNode *node) { + if (node) { + ucx_avl_free_node(al, node->left); + ucx_avl_free_node(al, node->right); + alfree(al, node); + } +} + +void ucx_avl_free(UcxAVLTree *tree) { + UcxAllocator *al = tree->allocator; + ucx_avl_free_node(al, tree->root); + alfree(al, tree); +} + void *ucx_avl_get(UcxAVLTree *tree, intptr_t key) { UcxAVLNode *n = tree->root; int cmpresult; @@ -143,7 +157,7 @@ } if (cmpresult) { - UcxAVLNode *e = malloc(sizeof(UcxAVLNode)); + UcxAVLNode *e = almalloc(tree->allocator, sizeof(UcxAVLNode)); e->key = key; e->value = value; e->height = 1; e->parent = e->left = e->right = NULL; ucx_avl_connect(tree, n, e, 0); @@ -155,7 +169,7 @@ return prevval; } } else { - tree->root = malloc(sizeof(UcxAVLNode)); + tree->root = almalloc(tree->allocator, sizeof(UcxAVLNode)); tree->root->key = key; tree->root->value = value; tree->root->height = 1; tree->root->parent = tree->root->left = tree->root->right = NULL; @@ -181,14 +195,15 @@ ucx_avl_connect(tree, s->parent, s->right, s->key); n->key = s->key; n->value = s->value; p = s->parent; + alfree(tree->allocator, s); } else { if (p) { ucx_avl_connect(tree, p, n->right ? n->right:n->left, n->key); } else { tree->root = n->right ? n->right : n->left; } + alfree(tree->allocator, n); } - // TODO: free the correct memory if (p) { ucx_avl_balance(tree, p);
--- a/ucx/avl.h Mon May 18 12:54:18 2015 +0200 +++ b/ucx/avl.h Mon May 18 18:39:19 2015 +0200 @@ -134,6 +134,12 @@ UcxAVLTree *ucx_avl_new_a(cmp_func cmpfunc, UcxAllocator *allocator); /** + * Destroys an UcxAVLTree. + * @param tree the tree to destroy + */ +void ucx_avl_free(UcxAVLTree *tree); + +/** * Macro for initializing a new UcxAVLTree with the default allocator and a * ucx_ptrcmp() compare function. *