简体   繁体   English

C中的动态内存分配问题

[英]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); 我在int* sortedArray = (int*)malloc(len);处得到一个断点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. 我两次使用malloc()在函数内创建两个不同的数组,当不再需要它们时,我在函数的末尾将它们都free() 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)); 也许你的意思是malloc(countLen * sizeof(int)); and malloc(len * sizeof(int)); malloc(len * sizeof(int)); ? malloc takes its size in bytes. malloc的大小以字节为单位。

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

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