orderedmap: fix memory leak when using orderedmap_remove()

closes #351
This commit is contained in:
rofl0r 2021-03-14 16:06:10 +00:00
parent 38934921c4
commit c4231e58bf
3 changed files with 17 additions and 2 deletions

View File

@ -156,6 +156,14 @@ htab_value* htab_find(struct htab *htab, const char* key)
return &e->item.data; return &e->item.data;
} }
htab_value* htab_find2(struct htab *htab, const char* key, char **saved_key)
{
struct elem *e = htab_find_elem(htab, key);
if(!e) return 0;
*saved_key = e->item.key;
return &e->item.data;
}
int htab_delete(struct htab *htab, const char* key) int htab_delete(struct htab *htab, const char* key)
{ {
struct elem *e = htab_find_elem(htab, key); struct elem *e = htab_find_elem(htab, key);

View File

@ -14,6 +14,8 @@ typedef union htab_value {
struct htab * htab_create(size_t); struct htab * htab_create(size_t);
void htab_destroy(struct htab *); void htab_destroy(struct htab *);
htab_value* htab_find(struct htab *, const char* key); htab_value* htab_find(struct htab *, const char* key);
/* same as htab_find, but can retrieve the saved key (for freeing) */
htab_value* htab_find2(struct htab *htab, const char* key, char **saved_key);
int htab_insert(struct htab *, char*, htab_value); int htab_insert(struct htab *, char*, htab_value);
int htab_delete(struct htab *htab, const char* key); int htab_delete(struct htab *htab, const char* key);
size_t htab_next(struct htab *, size_t iterator, char** key, htab_value **v); size_t htab_next(struct htab *, size_t iterator, char** key, htab_value **v);

View File

@ -81,14 +81,19 @@ char* orderedmap_find(struct orderedmap *o, const char *key) {
int orderedmap_remove(struct orderedmap *o, const char *key) { int orderedmap_remove(struct orderedmap *o, const char *key) {
size_t i; size_t i;
char *lk; char *lk;
htab_value *lv, *v = htab_find(o->map, key); char *sk;
char **sv;
htab_value *lv, *v = htab_find2(o->map, key, &sk);
if(!v) return 0; if(!v) return 0;
htab_delete(o->map, key); sv = sblist_get(o->values, v->n);
free(*sv);
sblist_delete(o->values, v->n); sblist_delete(o->values, v->n);
i = 0; i = 0;
while((i = htab_next(o->map, i, &lk, &lv))) { while((i = htab_next(o->map, i, &lk, &lv))) {
if(lv->n > v->n) lv->n--; if(lv->n > v->n) lv->n--;
} }
htab_delete(o->map, key);
free(sk);
return 1; return 1;
} }