aboutsummaryrefslogtreecommitdiff
path: root/collections/map/map.c
diff options
context:
space:
mode:
authorTucker Evans <tucker@tuckerevans.com>2020-07-06 20:07:45 -0400
committerTucker Evans <tucker@tuckerevans.com>2020-07-08 11:02:44 -0400
commit7d69ea177200bda62b403eb9ead6eee2ba5abe52 (patch)
treecad2e1fd9810ca300d7219230aa1819ce1ff11f2 /collections/map/map.c
parent51d368c20e1d93970a94cb0d2aff10654922bb37 (diff)
Add reset key function for maps
Allows changing the pointer to key when they are equivalent (by cmp function), to avoid memory leaks that could happen if we assumed either pointer was to be freed or overwritten.
Diffstat (limited to 'collections/map/map.c')
-rw-r--r--collections/map/map.c23
1 files changed, 23 insertions, 0 deletions
diff --git a/collections/map/map.c b/collections/map/map.c
index 83a446d..7de58e4 100644
--- a/collections/map/map.c
+++ b/collections/map/map.c
@@ -82,6 +82,29 @@ void *key, *val;
return 0;
}
+void* map_reset_key(root, key)
+map *root;
+void *key;
+{
+ void *tmp;
+ int cmp;
+
+ if (!root || !key)
+ return NULL;
+
+ cmp = root->cmp(root->key, key);
+
+ if (cmp < 0)
+ return map_reset_key(root->left, key);
+
+ if (cmp > 0)
+ return map_reset_key(root->right, key);
+
+ tmp = root->key;
+ root->key = key;
+ return tmp;
+}
+
void map_clear(root)
map *root;
{