繁体   English   中英

C free()在函数中导致段错误

[英]C free() causes segfault in function

 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

我做了countingSort,但是当我使用80、81行时,编译会导致如下错误。.我认为当我调用free()时,在99行之后存在一些问题

随机情况

之前:1 8 3 4 6 8 2 16

之后:1 2 3 4 6 8 8 16

升序

之前:1 2 3 4 5 6 7 8

细分错误:11

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

memset(numOfLessValue, 0, numOfLessValueSize);

应该:

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

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

关于这种类型的行:'numOfLessValue [arr [i]] ++;' 代码如何知道arr [i]的内容在numOfLessValue []数组的范围内? 当arr [i]在numOfLessValue []数组的范围之外时,则堆已损坏。 这就是导致段故障事件的原因

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM