I am trying to implement a sort function (counting sort, it is probably wrong):
void countingsortmm(int* numbers, int len, int min, int max) {
printf("Sorting %d integers with the min: %d and max: %d\n",len,min,max);
int countLen = max-min+1;
/* create an array to store counts for the occurences of a number. */
int* countingArray = (int*)malloc(countLen);
/* init all values to 0 */
for(int i = 0; i < countLen; i++) countingArray[i] = 0;
/* increment at indexes where a number occurs */
for(int i = 0; i < len; i++) countingArray[numbers[i]]++;
/* add previous indexes */
for(int i = 1; i < countLen; i++) countingArray[i] += countingArray[i-1];
/* Array where numbers will be places in a sorted order. */
int* sortedArray = (int*)malloc(len);
/* put numbers in proper place in new array and decrement */
for(int i = len-1; i >= 0; i--) sortedArray[countingArray[numbers[i]]--] = numbers[i];
/* copy contents of new sorted array to the numbers parameter. */
for(int i = 0; i < len-1; i++) numbers[i] = sortedArray[i];
free(sortedArray);
free(countingArray);
}
But I get the following error:
malloc: *** error for object 0x7f8728404b88: incorrect checksum for freed object - object was probably modified after being freed.
I get a break-point at int* sortedArray = (int*)malloc(len);
.
I use malloc()
twice to create two different arrays within the function and I free()
them both at the end of the function when they are no longer needed. I do not explicitly modify or access their contents afterwards.
So what is causing this problem?