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

标签 c hashtable

我正在尝试用 C 实现链式哈希表。这是类(class)中的一个项目,因此它不必是完美的,但我无法让它工作。

在我向哈希表添加新值的方法中,一切似乎都正常,但后来当我尝试在哈希表中查找某些值时,里面似乎什么也没有(或一些垃圾值)。我认为哈希函数工作正常,所以我不会发布它。相关代码如下:

// 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;
}

如果我能得到任何帮助,我将不胜感激,因为我已经为此苦苦挣扎了两天......谢谢:)

最佳答案

您正在分配一个新节点

node* new_node = malloc(sizeof(node));
new_node->value = value;

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

尝试类似的事情

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,则使用 gcc -Wall -g )并学习如何使用调试器(例如 gdb )。

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

最后不知道insert_node怎么样了叫?我猜(如 joop 评论)您可能想要复制该字符串,例如使用new_node->value = strdup(value);

关于c - C 中的哈希表实现 - 里面只有垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25620761/

相关文章:

c - GCC/x86 内联汇编 : How do you tell gcc that inline assembly section will modify %esp?

c# - 如何在 Linq 中使用哈希表

c# - 如何在 C# 中将 List<object> 转换为 Hashtable?

c++ - 混淆在C++中实现rehash()函数

c - 将 strcpy() 与结构数组(及其元素)一起使用不起作用

c - 隐式类型转换是否会改变变量的大小

python - 在字典/ HashMap 中(在Python中)使用对象作为自己的键是否正常?

hashtable - 哈希表线性探测的运行时间

c - 为什么我的代码取消了这部分代码的注释

c - unsafePerformIO 和 FFI 库初始化