Fix some code bugs (#1021)

* fix(counting_sort.c): Fix access out-of-bounds issue

* fix(hash_map_open_addressing.c): Fix coding errors

* fix(binary_search_tree.c): Fix unreleased memory

* Update indentataion
pull/1024/head
gonglja 11 months ago committed by GitHub
parent ef40418129
commit 3a559f1b60
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -111,7 +111,7 @@ void put(HashMapOpenAddressing *hashMap, int key, char *val) {
// 若找到键值对,则覆盖 val 并返回 // 若找到键值对,则覆盖 val 并返回
if (hashMap->buckets[index] != NULL && hashMap->buckets[index] != hashMap->TOMBSTONE) { if (hashMap->buckets[index] != NULL && hashMap->buckets[index] != hashMap->TOMBSTONE) {
free(hashMap->buckets[index]->val); free(hashMap->buckets[index]->val);
hashMap->buckets[index]->val = (char *)malloc(sizeof(strlen(val + 1))); hashMap->buckets[index]->val = (char *)malloc(sizeof(strlen(val) + 1));
strcpy(hashMap->buckets[index]->val, val); strcpy(hashMap->buckets[index]->val, val);
hashMap->buckets[index]->val[strlen(val)] = '\0'; hashMap->buckets[index]->val[strlen(val)] = '\0';
return; return;
@ -119,7 +119,7 @@ void put(HashMapOpenAddressing *hashMap, int key, char *val) {
// 若键值对不存在,则添加该键值对 // 若键值对不存在,则添加该键值对
Pair *pair = (Pair *)malloc(sizeof(Pair)); Pair *pair = (Pair *)malloc(sizeof(Pair));
pair->key = key; pair->key = key;
pair->val = (char *)malloc(sizeof(strlen(val + 1))); pair->val = (char *)malloc(sizeof(strlen(val) + 1));
strcpy(pair->val, val); strcpy(pair->val, val);
pair->val[strlen(val)] = '\0'; pair->val[strlen(val)] = '\0';

@ -18,7 +18,7 @@ void countingSortNaive(int nums[], int size) {
} }
// 2. 统计各数字的出现次数 // 2. 统计各数字的出现次数
// counter[num] 代表 num 的出现次数 // counter[num] 代表 num 的出现次数
int *counter = calloc(m, sizeof(int)); int *counter = calloc(m + 1, sizeof(int));
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
counter[nums[i]]++; counter[nums[i]]++;
} }

@ -117,6 +117,8 @@ void removeItem(BinarySearchTree *bst, int num) {
} else { } else {
pre->right = child; pre->right = child;
} }
// 释放内存
free(cur);
} else { } else {
/* 子节点数量 = 2 */ /* 子节点数量 = 2 */
// 获取中序遍历中 cur 的下一个节点 // 获取中序遍历中 cur 的下一个节点

Loading…
Cancel
Save