释放 arr 返回错误 malloc: *** 释放对象指针的错误未分配

时间:2021-01-09 17:21:07

标签: c malloc

我正在尝试编写一个函数,该函数接受 2 个数组及其大小(大小相同),并返回一个数组,其中第一个数组中的每个数字出现在第二个数组中相同索引中的次数。示例:输入:{2,5,3,7,8},{5,2,0,4,3},5 输出:{2,2,2,2,2,5,5,7,7, 7,7,8,8,8}

我当前的代码:

#include <stdio.h>
#include <stdlib.h>

int* blowUpArray(int numArray[], int amountArray[], int size);
int* reallocateArr(int* arr, int currLogSize, int newSize);

int main() {
    int arr1[] = {2,5,3,7,8},arr2[] = {5,2,0,4,3}
    int* res;
    res = blowUpArray(arr1,arr2,5);
    for (int i = 0; i < 14; i++)
        printf("%d ", res[i]);
    return 0;
}

int* blowUpArray(int numArray[], int amountArray[], int size)
{
    int i = 0,currSize = 0,j;
    int* blownUp;
    while (i < size)
    {
        blownUp = reallocateArr(numArray,currSize,amountArray[i]);
        for (j = currSize; j < currSize + amountArray[i]; j++)
        {
            blownUp[j] = numArray[i];
        }
        currSize = currSize + amountArray[i];
        i++;
    }
    return blownUp;
}

int* reallocateArr(int* arr, int currLogSize, int addedSize)
{
    int* newArr;
    int i;

    newArr = (int*)malloc((currLogSize + addedSize) * sizeof(int));

    if (newArr == NULL)
    {
        printf("Memory allocation failed.\n");
        exit(1);
    }

    for (i = 0; i < currLogSize; i++)
        newArr[i] = arr[i];

    free(arr);

    return newArr;
}

我收到此错误:

malloc: *** error for object 0x7ffee644b6f0: pointer being freed was not allocated
malloc: *** set a breakpoint in malloc_error_break to debug

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

reallocateArr 函数正在释放 arr 参数。它是这样调用的:

reallocateArr(numArray,currSize,amountArray[i]);

其中 numArray 是函数 blowUpArray 的参数,其调用方式如下:

res = blowUpArray(arr1,arr2,5);

其中 arrmain 函数的局部数组。因为这个数组被声明为一个局部变量,所以你不能把它传递给 free

您可能想将 blownUp 传递给 reallocateArr

reallocateArr(blownUp,currSize,amountArray[i]);

您还应该将此变量初始化为 NULL

int* blownUp = NULL;

因此您可以在 free 中循环的第一次迭代时安全地将其传递给 blowUpArray