gpt4 book ai didi

C free() 导致函数段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:54 29 4
gpt4 key购买 nike

 48 void countingSort(int *arr, int size, int maxValue)
49 {
50 if (arr == NULL || size < 0)
51 {
52 perror("countingSort() invalid arguments");
53 return;
54 }
55
56 int numOfLessValueSize = maxValue + 1;
57 int * numOfLessValue = (int *)malloc(sizeof(int) * numOfLessValueSize);
58 memset(numOfLessValue, 0, numOfLessValueSize);
59 int * resultArray = (int *)malloc(sizeof(int) * size);
60 int i = 0;
61
62 // init numOfLessValue, count each value
63 for (i = 0; i < size; ++i)
64 numOfLessValue[arr[i]]++;
65
66 // init numOfLessValue, accumulate values
67 for (i = 0; i < maxValue; ++i)
68 numOfLessValue[i + 1] += numOfLessValue[i];
69
70 // use numOfLessValue, to countingSort
71 for (i = 0; i < size; ++i)
72 {
73 int inputIndex = numOfLessValue[arr[i]]--;
74 resultArray[--inputIndex] = arr[i];
75 }
76
77 for (i = 0; i < size; ++i)
78 arr[i] = resultArray[i];
79
80 // free(numOfLessValue);
81 // free(resultArray);
82 }

void testCountingSort()
85 {
86 int randomArray[SIZE] = {1,8,3,4,6,8,2,16};
87 int ascendantArray[SIZE] = {1,2,3,4,5,6,7,8};
88 int descendantArray[SIZE] = {8,7,6,5,4,3,2,1};
89 int sameValueArray[SIZE] = {1,1,1,1,1,1,1,1};
90 int maxValue = 0;
91
92 printf("random case\n");
93 printf("before : "); printArray(randomArray, SIZE);
94 maxValue = getMaxValue(randomArray, SIZE);
95 countingSort(randomArray, SIZE, maxValue);
96 printf("after : "); printArray(randomArray, SIZE);
97
98 printf("\nascendant order\n");
99 printf("before : "); printArray(ascendantArray, SIZE);
100 maxValue = getMaxValue(ascendantArray, SIZE);
101 countingSort(ascendantArray, SIZE, maxValue);
102 printf("after : "); printArray(ascendantArray, SIZE);
103

i made countingSort, but when I use line 80, 81 then compile causes error like below.. I think when I call free() then it has some problem after line 99

random case

before : 1 8 3 4 6 8 2 16

after : 1 2 3 4 6 8 8 16

ascendant order

before : 1 2 3 4 5 6 7 8

Segmentation fault: 11

我不明白为什么会发生这些事情。请帮助我。

最佳答案

memset(numOfLessValue, 0, numOfLessValueSize);

应该是:

memset(numOfLessValue, 0, numOfLessValueSize * sizeof(int));

更好的是,只需使用 calloc 而不是 malloc

关于C free() 导致函数段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29577450/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com