C free() 导致函数段错误

标签 c

 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/

相关文章:

python - 尝试从 C 调用 Python

c - 您如何解释我的 C 哈希函数(Fowler–Noll–Vo_hash_function 类型)的行为?

c - 哪些 int 值与 C 中的 exit() 相关?

C 编程 : for loop and break

c - Sprintf 关于格式化的警告

c++ - 结构/对象内的存储顺序

c - 一次将数据写入多个套接字(一个系统调用)

c - 末尾显示随机字符的数组

c - 有没有办法在 C 的同一个头文件中包含静态原型(prototype)和公共(public)原型(prototype)?

c - 如何在 C 中将整数转换为数字数组?