首页 > 解决方案 > 用奇怪的段错误在 C 中实现哈希表

问题描述

我正在尝试在 C 中创建一个哈希表,并且我想记录一个包含表的每个唯一键的链表。但是,在我用来检查键是否已经在链表中的 while 循环开始时,我遇到了段错误。谁能明白这里发生了什么?

提前道歉:ull 是 unsigned long long

h_keys 是一个全局变量,

段错误发生在此 while 循环的开始。

void put_in_key(ull address){
    struct mem_node * cur = h_keys;
    ull key = hash_func(address);
    printf("ok %lld\n",address);
    while(cur){
        //printf("stuck in here?\n");
        if(cur->key==key){ // key already in hashtable keys
            return;
        }
        cur=cur->next;
    }
    struct mem_node* newkey = malloc(sizeof(struct mem_node *));
    if(newkey==NULL){
        printf("big trouble");
    }
    newkey->key=key;
    cur->next=newkey;
}

这是结构

struct mem_node{ // add one of these each time we get a new window
    ull address;
    ull page;
    ull key;
    struct mem_node * next;
};

这是 h_keys 的声明

h_keys=malloc(sizeof(struct mem_node*));

然后根据输入,我有时会到达另一个计算链表长度的函数的一部分。但是,我在这里的 while 循环的第一行也遇到了段错误。

struct mem_node* counter = h_keys;
        ull uniques=0;
        while(counter!=NULL && counter->next!=NULL){
            printf("whafs da %lld\n",uniques);
        
            //printf("%lld\n",counter->key);
            //printf("%lld \n",counter->ne)
            fflush(stdout);
            uniques++;
            counter=counter->next;
        }

标签: clinked-listhashmapmallochashtable

解决方案


推荐阅读