C中的哈希表实现 - 只有里面的垃圾值

时间:2014-09-02 10:03:28

标签: c hashtable

我正在尝试在C中实现一个Chained哈希表。这是一个来自课程的项目,所以它不一定是完美的,但我无法让它工作。

在我向哈希表添加新值的方法中,一切似乎都没问题,但后来当我尝试在哈希表中找到一些值时,似乎内部没有任何内容(或一些垃圾值)。我认为哈希函数正常工作所以我不会发布它。以下是相关代码:

// typedef a node for the linked list
typedef struct node
{
    char* value;
    struct node* next;
}
node;

// global variables
node* head = NULL;
node* lists[145000];

// this method inserts a new value into the hash table
bool insert_word(char* value, int index)
{
    // inserting at the beginning of the list
    node* new_node = malloc(sizeof(node));
    new_node->value = value;

    if (head == NULL)
    {
        head = new_node;
    }
    else
    {
        new_node->next = head;
        head = new_node;
    }

    lists[index] = head;

    return true;
}

// this method should check if the searched word
// is present in the hash table
bool check(const char* word)
{
    int index = hash(word);

    node* curr_node = lists[index];

    while (curr_node != NULL)
    {
        if (strcmp(curr_node->value, word) == 0) // this never happens
        {
            return true;
        }
        curr_node = curr_node->next;
    }

    return false;
}

我很感激任何帮助,因为我已经为这两天苦苦挣扎......谢谢:)。

1 个答案:

答案 0 :(得分:1)

您正在

中分配新节点
node* new_node = malloc(sizeof(node));
new_node->value = value;

但是您没有测试malloc的失败,并且您并不总是设置next的{​​{1}}字段(因此当new_node为{head时,该字段可能包含垃圾{1}})。

尝试类似

的内容
NULL

最重要的是,使用所有警告和调试信息进行编译(例如,如果使用GCC,则使用node* new_node = malloc(sizeof(node)); if (!new_node) {perror("malloc node"); exit(EXIT_FAILURE); }; new_node->value = value; // probably needs:: strdup (value) new_node->next = NULL; )并了解如何使用调试器(例如gcc -Wall -g )。

还使用内存泄漏检测器,如valgrind ...

最后,我们不知道如何调用gdb?我想(比如joop评论)你可能想要复制字符串,例如使用insert_node