Skip to content

Commit

Permalink
htab: have dt_htab_destroy del all the elements
Browse files Browse the repository at this point in the history
This means that a dt_htab_destroy of a non-empty htab doesn't leak memory
and leave all its former elements full of wild pointers.

Also add some comments to dt_htab_delete given how many mistakes I made
reading it.

Signed-off-by: Nick Alcock <nick.alcock@oracle.com>
Reviewed-by: Eugene Loh <eugene.loh@oracle.com>
Reviewed-by: Kris Van Hees <kris.van.hees@oracle.com>
  • Loading branch information
nickalcock authored and kvanhees committed Dec 1, 2021
1 parent 4c66cfe commit c5b9b89
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion libdtrace/dt_htab.c
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,29 @@ dt_htab_t *dt_htab_create(dtrace_hdl_t *dtp, dt_htab_ops_t *ops)
}

/*
* Destroy a hashtable.
* Destroy a hashtable, deleting all its entries first.
*/
void dt_htab_destroy(dtrace_hdl_t *dtp, dt_htab_t *htab)
{
size_t i;

if (!htab)
return;

for (i = 0; i < htab->size; i++) {
dt_hbucket_t *bucket = htab->tab[i];

while (bucket) {
dt_hbucket_t *obucket = bucket;

while (bucket->head)
bucket->head = htab->ops->del(bucket->head,
bucket->head);
bucket = bucket->next;
free(obucket);
};
}

dt_free(dtp, htab->tab);
dt_free(dtp, htab);
}
Expand Down Expand Up @@ -193,6 +209,10 @@ int dt_htab_delete(dt_htab_t *htab, void *entry)
dt_hbucket_t *bucket;
void *head;

/*
* Find the right bucket in cases of hash collision.
*/

for (bucket = htab->tab[idx]; bucket; bucket = bucket->next) {
if (htab->ops->cmp(bucket->head, entry) == 0)
break;
Expand All @@ -201,9 +221,16 @@ int dt_htab_delete(dt_htab_t *htab, void *entry)
if (bucket == NULL)
return -ENOENT;

/*
* Delete the specified entry, now known to be in this bucket.
*/
head = htab->ops->del(bucket->head, entry);
bucket->nentries--;
htab->nentries--;

/*
* Deal with a now-empty bucket.
*/
if (!head) {
dt_hbucket_t *b = htab->tab[idx];

Expand Down

0 comments on commit c5b9b89

Please sign in to comment.