krahets / hello-algo

《Hello 算法》:动画图解、一键运行的数据结构与算法教程。支持 Python, Java, C++, C, C#, JS, Go, Swift, Rust, Ruby, Kotlin, TS, Dart 代码。简体版和繁体版同步更新,English version ongoing
https://hello-algo.com
Other
86.33k stars 10.95k forks source link

hello-algo/codes/c/chapter_hashing /hash_map_open_addressing.c运行出现段错误 #1354

Closed spectrumzero closed 1 month ago

spectrumzero commented 2 months ago

似乎有两处忘记对桶进行初始化,导致了段错误: 第一处:

/* 构造函数 */
HashMapOpenAddressing *newHashMapOpenAddressing() {
    HashMapOpenAddressing *hashMap = (HashMapOpenAddressing *)malloc(sizeof(HashMapOpenAddressing));
    hashMap->size = 0;
    hashMap->capacity = 4;
    hashMap->loadThres = 2.0 / 3.0;
    hashMap->extendRatio = 2;
    hashMap->buckets = (Pair **)malloc(sizeof(Pair *) * hashMap->capacity);  //需要修改的地方
    hashMap->TOMBSTONE = (Pair *)malloc(sizeof(Pair));
    ...
}

第二处:

/* 扩容哈希表 */
void extend(HashMapOpenAddressing *hashMap) {
    // 暂存原哈希表
    Pair **bucketsTmp = hashMap->buckets;
    int oldCapacity = hashMap->capacity;
    // 初始化扩容后的新哈希表
    hashMap->capacity *= hashMap->extendRatio;
    hashMap->buckets = (Pair **)malloc(sizeof(Pair *) * hashMap->capacity);  //需要修改的地方
    hashMap->size = 0;
    ...
}

修改:在要修改的位置的下一行添加如下代码:

for (int i = 0; i < hashMap->capacity; i++) 
{ 
    hashMap->buckets[i] = NULL;
}
Gonglja commented 2 months ago

感谢建议,已经pr https://github.com/krahets/hello-algo/pull/1367