I try to create a function that get in input an hash table and return a linked list of keys. This is the struct of a list node:
struct hash_table_key_list_node_s {
char *key;
struct hash_table_key_list_node_s* next;
};
typedef struct hash_table_key_list_node_s hash_table_key_list_node_t;
typedef hash_table_key_list_node_t* hash_table_key_list_t;
I don't understand why the list contains only one element but the hash table contains 330 element. This is the code of the function:
hash_table_key_list_t hash_table_keys(hash_table_t hash_table) {
hash_table_key_list_t list, tail, p;
list = tail = NULL;
if ( hash_table != NULL && hash_table->slots != NULL ) {
size_t index = 0;
while ( index < hash_table->capacity ) {
hash_table_list_node_t *node = hash_table->slots[index].head;
while ( node != NULL ) {
p = malloc(sizeof(hash_table_key_list_node_t));
p->key = strdup(node->key);
if ( node != NULL ) {
list = tail = p;
}
else {
tail->next = p;
tail = p;
}
node = node->next;
}
index++;
}
}
return list;
}
There's a bug in you list insertion logic:
if (node != NULL) {
Should be:
if (list == NULL) {
As node
is always not NULL
at this point as it's the condition for you loop and you actually want to check if this is the first entry to be inserted into the new link list (checking if list
is NULL
will achieve this). Note you should also check if your malloc
and strdup
are successful before adding it to the list, cleaning up the link list (freeing allocated part of the list) and returning some kind of error indication if there isn't enough memory to create the list from the table.