Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
spectrumzero opened this issue May 9, 2024 · 1 comment

Comments

@spectrumzero
Copy link

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

/* 构造函数 */
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
Copy link
Contributor

Gonglja commented May 15, 2024

感谢建议,已经pr #1367

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants