fix(hash_map): fixed leak on value update

This commit is contained in:
william.valenduc 2026-01-19 15:28:35 +00:00
parent 3cf1960a00
commit 2ebf56dde7
4 changed files with 251 additions and 13 deletions

View file

@ -55,7 +55,7 @@ struct hash_map *hash_map_init(size_t size)
bool hash_map_insert(struct hash_map *hash_map, const char *key, void *value,
bool *updated)
{
if (hash_map == NULL || hash_map->size == 0 || key == NULL)
if (hash_map == NULL || hash_map->size == 0 || key == NULL || value == NULL)
return false;
size_t h = hash(key);
@ -71,6 +71,7 @@ bool hash_map_insert(struct hash_map *hash_map, const char *key, void *value,
if (strcmp(iter->key, key) == 0)
{
// update
free(iter->value);
iter->value = value;
if (updated)
*updated = true;
@ -96,16 +97,16 @@ bool hash_map_insert(struct hash_map *hash_map, const char *key, void *value,
return true;
}
void hash_map_free(struct hash_map *hash_map)
void hash_map_free(struct hash_map **hash_map)
{
struct pair_list *l;
struct pair_list *prev;
if (hash_map)
if (hash_map != NULL && *hash_map != NULL)
{
for (size_t i = 0; i < hash_map->size; i++)
for (size_t i = 0; i < (*hash_map)->size; i++)
{
l = hash_map->data[i];
l = (*hash_map)->data[i];
while (l != NULL)
{
prev = l;
@ -113,8 +114,8 @@ void hash_map_free(struct hash_map *hash_map)
destroy_pair_list(&prev);
}
}
free(hash_map->data);
free(hash_map);
free((*hash_map)->data);
free(*hash_map);
}
}