微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Leetcode Segmentation fault 试图在调用之间重置哈希表数据结构部分解决

如何解决Leetcode Segmentation fault 试图在调用之间重置哈希表数据结构部分解决

我在 Leetcode 上做一个 problem。它说我通过了我的第一个测试用例,但我的第二个测试用例失败了,答案很简单。当我手动运行那个案例时,我通过了,所以我知道这与它们运行之间的数据持久性有关。这显然是我正在使用的哈希表,我首先在全局声明了它。为了解决这个问题,我首先尝试使用 calloc 和 memset 将其重置为零,但出现了段错误

我认为合乎逻辑的事情是在调用函数内创建哈希,所以每次调用它时都会重新初始化。但是,即使它看起来应该可以工作,我仍然收到段错误错误(地址消毒剂致命信号)。我是否滥用指针?

这是我的代码不起作用。注释 //\ 代表我之前的代码行,它逐案工作。没有太多变化——主要是为了返回哈希。我评论了 seg 错误发生的位置(根据我的 printf 调试)。我希望我没有错过任何东西。我试图将两个编码实例合二为一,因为它大多是冗余的。

#define SIZE 1000

typedef struct htent{
    struct htent* next;
    int key,value;
    
} htent;

int hashf(int val,int size){
    return val % SIZE; // don't need anything fancy
}

htent* create_new_htent(int val){ // the value is its own key
    htent* ent = malloc(sizeof(htent));
    ent->next = NULL;
    ent->key = val;
    ent->value = val;
    return ent;
}
// htent* ht[SIZE] = {0}; //\\ This was my method before (main difference)
htent* build_hash_table_n_get_lowest(int* nums,int numsSize,int* low){ //\\ returned void before
    htent* ht[SIZE] = {0}; //\\ before was commented out
    int hash;
    int running_low = 10000; // large #
    htent* tmp;
    for (int i = 0; i < numsSize; i++){
        if (nums[i] < 1 ) continue; // drop negatives
        if (nums[i] < running_low) running_low = nums[i];
        printf("%d: Running Low %d\n",i,running_low);
        htent* ent = create_new_htent(nums[i]);
        hash = hashf(nums[i],numsSize);
        if (ht[hash] == NULL){ 
            ht[hash] = ent; // singly linked list 
            continue;
        }
        tmp = ht[hash];
        while(tmp->next != NULL){
            tmp = tmp->next;
        }
        tmp->next = ent;
    }
    *low = running_low;
    return ht; //\\ was commented out before
}
    
int find_missing_lowest(htent** ht,int lowest){
    int moving_target = 1;
    for (int i = 0; i<numsSize; i++){
        if (ht[moving_target] == NULL){   // SEG FAULTS HERE!!!
         return moving_target;
        }
        moving_target++;
    }
    return moving_target;
}
    

int firstMissingPositive(int* nums,int numsSize){ // Function Leetcode calls 
    int lowest;
    htent* ht = build_hash_table_n_get_lowest(nums,numsSize,&lowest); // tried with htent**
    return find_missing_lowest(ht,lowest);
    
    
    }

编辑:我使用全局作用域方法构建了这个函数,它可以工作并且这些测试通过(只需要处理边缘情况),但必须有更好的方法

void refresh_hashtable(){
    for (int i = 0; i<SIZE; i++){
        ht[i] = NULL;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。