Skip to content

check for the HT_DELETED_ITEM too while deleting hash table. #53

Description

@rohitsutreja

Author has written ht_del_hash_table function as below.

void ht_del_hash_table(ht_hash_table* ht) {
    for (int i = 0; i < ht->size; i++) {
        ht_item* item = ht->items[i];
        if (item != NULL) {
            ht_del_item(item);
        }
    }
    free(ht->items);
    free(ht);
}

But there is a problem, when we later add function to delete an item from the hash table, we do it via making the pointer equal to HT_DELETED_ITEM.

So if we delete an item from hash table and then after delete the whole table then it will be segment fault. Becuase above function only checks for NULL, the item pointing to HT_DELETED_ITEM will be passed to ht_del_item function. That function is as following.

static void ht_del_item(ht_item* i) {
    free(i->key);
    free(i->value);
    free(i);
}

this will try to free the HT_DELETED_ITEM and result in segment fault.

I think we should add the check for HT_DELETED_ITEM too.

Correct function should be :

void ht_del_hash_table(ht_hash_table *ht) {
  for (int i = 0; i < ht->size; ++i) {
    ht_item* item = ht->items[i];
    if (item  != NULL && item  != &HT_DELETED_ITEM) {
      ht_del_item(item);
    }
  }

  free(ht->items);
  free(ht);
}

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