简体   繁体   中英

Issue with dynamic memory allocation in C

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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