0

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?

aanrv
  • 2,159
  • 5
  • 25
  • 37
  • @Cornstalks: Why didn't you write your comment as an answer instead, seeing as how it is indeed the correct answer? :) – Dolda2000 Mar 13 '15 at 21:28
  • 1
    @Dolda2000: I'm not sure... I guess I was just too lazy to scroll down the extra amount to the answer area? – Cornstalks Mar 13 '15 at 21:30
  • 2
    please [do not cast](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) the return value of `malloc()`. – Sourav Ghosh Mar 13 '15 at 21:30

1 Answers1

3

It means you're corrupting your heap. Perhaps you meant malloc(countLen * sizeof(int)); and malloc(len * sizeof(int));? malloc takes its size in bytes.

Cornstalks
  • 37,137
  • 18
  • 79
  • 144