diff --git a/codes/c/chapter_hashing/array_hash_map.c b/codes/c/chapter_hashing/array_hash_map.c index cb2d8a9058..3853ef00b3 100644 --- a/codes/c/chapter_hashing/array_hash_map.c +++ b/codes/c/chapter_hashing/array_hash_map.c @@ -92,7 +92,7 @@ void pairSet(ArrayHashMap *hmap, MapSet *set) { for (i = 0; i < HASHTABLE_CAPACITY; i++) { if (hmap->buckets[i] != NULL) { entries[index].key = hmap->buckets[i]->key; - entries[index].val = malloc(strlen(hmap->buckets[i]->val + 1)); + entries[index].val = malloc(strlen(hmap->buckets[i]->val) + 1); strcpy(entries[index].val, hmap->buckets[i]->val); index++; } diff --git a/codes/c/chapter_sorting/counting_sort.c b/codes/c/chapter_sorting/counting_sort.c index 73ba54f0a1..54aed970a1 100644 --- a/codes/c/chapter_sorting/counting_sort.c +++ b/codes/c/chapter_sorting/counting_sort.c @@ -18,7 +18,7 @@ void countingSortNaive(int nums[], int size) { } // 2. 统计各数字的出现次数 // counter[num] 代表 num 的出现次数 - int *counter = malloc(sizeof(int) * m); + int *counter = calloc(m, sizeof(int)); for (int i = 0; i < size; i++) { counter[nums[i]]++; } @@ -29,6 +29,9 @@ void countingSortNaive(int nums[], int size) { nums[i] = num; } } + + // 4. 释放内存 + free(counter); } /* 计数排序 */ @@ -43,7 +46,7 @@ void countingSort(int nums[], int size) { } // 2. 统计各数字的出现次数 // counter[num] 代表 num 的出现次数 - int *counter = malloc(sizeof(int) * m); + int *counter = calloc(m, sizeof(int)); for (int i = 0; i < size; i++) { counter[nums[i]]++; } @@ -62,6 +65,9 @@ void countingSort(int nums[], int size) { } // 使用结果数组 res 覆盖原数组 nums memcpy(nums, res, size * sizeof(int)); + + // 5. 释放内存 + free(counter); } /* Driver Code */