C 中的动态内存分配问题

Issue with dynamic memory allocation in C

我正在尝试实现一个排序功能(计数排序,可能是错误的):

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);
}

但我收到以下错误:

malloc: *** error for object 0x7f8728404b88: incorrect checksum for freed object - object was probably modified after being freed.

我在 int* sortedArray = (int*)malloc(len); 处找到一个断点。

我使用 malloc() 两次在函数内创建两个 不同的 数组,我 free() 它们都在函数的末尾,当它们不存在时需要更长的时间。之后我不会明确修改或访问它们的内容。

那么是什么导致了这个问题?

这意味着您正在破坏您的堆。也许您指的是 malloc(countLen * sizeof(int));malloc(len * sizeof(int));malloc 以字节为单位。