Skip to content

Bug: ht_delete() decrements count even when the key is not found #61

Description

@ISystemNoTool

problem::

void ht_delete(ht_hash_table *ht, const char *key) {
    int index = ht_get_hash(key, ht->size, 0);
    ht_item *item = ht->items[index];

    while (item != NULL) {
        // ...
    }

    ht->count--;
}

In ht_delete(), ht->count -- is executed unconditionally at the end of the function.
This means that even if the target key does not exist in the hash table, the table's count will still be decreased.
expected behavior:
ht->count should only be decremented when an item is actually found and deleted.
Suggested fix
Move ht->count-- inside the successful deletion branch.

if (strcmp(item->key, key) == 0) {    
      ht_del_item(item);    
      ht->items[index] = &HT_DELETE_ITEM;   
      ht->count--;    return;}```

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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