From a0a1310f53114c9130c375e074c9f4d0e578fd86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20LUDWIG?= Date: Thu, 3 Aug 2023 23:17:54 +0200 Subject: [PATCH] feat: add hash_map_free --- lib/hash_map.c | 9 +++++++++ lib/hash_map.h | 6 ++++++ lib/linked_list.c | 1 + lib/string.c | 1 + test/hash_map_test.c | 1 + 5 files changed, 18 insertions(+) diff --git a/lib/hash_map.c b/lib/hash_map.c index cab21e1..67a781e 100644 --- a/lib/hash_map.c +++ b/lib/hash_map.c @@ -217,3 +217,12 @@ string_t *hash_map_get_keys(struct hash_map *hash_map) { } return keys; } + +void hash_map_free(struct hash_map *hash_map) { + for (size_t index = 0; index < hash_map->capacity; index++) { + if (hash_map->items[index] != NULL) { + linked_list_free(hash_map->items[index]); + } + } + free(hash_map); +} diff --git a/lib/hash_map.h b/lib/hash_map.h index 8981601..71bac7e 100644 --- a/lib/hash_map.h +++ b/lib/hash_map.h @@ -89,4 +89,10 @@ bool hash_map_contains_key(struct hash_map *hash_map, string_t key); */ string_t *hash_map_get_keys(struct hash_map *hash_map); +/** + * @brief Frees the hash map. + * @since v2.1.0 + */ +void hash_map_free(struct hash_map *hash_map); + #endif diff --git a/lib/linked_list.c b/lib/linked_list.c index e3298d7..5fd98cc 100644 --- a/lib/linked_list.c +++ b/lib/linked_list.c @@ -92,5 +92,6 @@ void linked_list_free(struct linked_list *list) { node_current = node_current->next; free(node_to_remove); } + list->head = NULL; free(list); } diff --git a/lib/string.c b/lib/string.c index 16fba0a..b076e38 100644 --- a/lib/string.c +++ b/lib/string.c @@ -285,6 +285,7 @@ bool string_get_has_unique_characters(const string_t string_value) { hash_map_add(characters_already_seen, key, (void*)true); } } + hash_map_free(characters_already_seen); return has_unique; } diff --git a/test/hash_map_test.c b/test/hash_map_test.c index 25411e0..4074127 100644 --- a/test/hash_map_test.c +++ b/test/hash_map_test.c @@ -24,4 +24,5 @@ void hash_map_test() { hash_map_remove(hash_map, "key5"); assert(hash_map->length == 5); assert(!hash_map_contains_key(hash_map, "key5")); + hash_map_free(hash_map); }