Skip to content

HASH_CLEAR-with-deleter #221

@Quuxplusone

Description

@Quuxplusone

The currently supported ways to clean up a populated hash are:

(1) If deletion/freeing of elements is needed, then

HASH_ITER(hh, myset, item, tmp) {
    HASH_DEL(myset, item);
    delete_or_free(item);
}

(2) If deletion/freeing is a no-op, then

HASH_CLEAR(hh, myset);

However, the former is slow and the latter is incorrect-if-freeing-is-needed. So the programmer (well, me) might think to write (3?!)

auto *first = myset;
HASH_ITER(hh, myset, item, tmp) {
    if (item != first) delete_or_free(item);
}
HASH_CLEAR(hh, myset);
delete_or_free(first);

Right now this works (I think), but it's not "supported" — uthash does not explicitly guarantee that HASH_CLEAR won't look at the prev/next pointers in myset (which are all now dangling and unsafe to read). It would be nice to add a "supported" method for cleaning up a hash table with deletion/freeing. Something like this:

HASH_FREE_AND_CLEAR(hh, myset, item, delete_or_free(item));

or simply

HASH_FREE_AND_CLEAR(hh, myset, delete_or_free);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions