C:Merge Sort实现中的错误 - 内存分配

时间:2014-02-25 17:23:32

标签: c malloc free mergesort

C中的Merge Sort实现中的内存分配(而不是释放问题)。这是代码的链接:http://ideone.com/UTjil7

代码太长了,无法粘贴在这里,无论如何这里是主要的内存问题:

int *MergeSort(int *A, int x, int y) //declaration
{
if(x==y) //base case, return the 1-element array itself
{
    return A;
}

else
{
    int size=1+y-x; //total no. of elements
    int half=(x+y)/2; //halving the array

    int halfsize=(size/2);
    int *A1=(int *)malloc(halfsize*sizeof(int));
    int *A2=(int *)malloc((size-halfsize)*sizeof(int)); 
    A1=MergeSort(A, x, half);           //calling MergeSort on 1st half of array
    A2=MergeSort(A, half+1, y);     //calling MergeSort on 2nd half of array


    int *C;                                 //pointer to 3rd array
    C=(int *)malloc(size*sizeof(int));
    int j=0;            //indicator for first half
    int k=0;            //indicator for 2nd half
    int i=0;            //indicator for 3rd array


    while((j<=half)&&(k<=half))         //till all the elements from either half are not exhausted
    {
        if(A1[j]<=A2[k])                    //if element of first half is smaller, put that in C
        {
            C[i]=A1[j];
            j++;
        }
        else                    //otherwise put element of second half in C
        {
            C[i]=A2[k];
            k++;
        }
        i++;                //increment indicator for C
    }
    int flag;
    if(j==(half+1))
    {
        flag=1;
    }
    else if(k==(half+1))
    {
        flag=2;
    }
    if(flag==1)         //if first half is finished
    {
        while(i<size)       //transfer all elements of second half in C
        {
            C[i]=A2[k];
            i++;
            k++;
        }

    }
    else if(flag==2) //if second half is finished
    {
        while(i<size) //transfer all elements of 1st half in C
        {
            C[i]=A1[j];
            i++;
            j++;
        }
    }


    for(int i=x;i<=y;i++) //copyback
    {
        A[x]=C[i-x];
    }
    free(A1); //Line 105
    free(A2); //Line 106
    free(C);
    return A;
}

}

它在输入并尝试运行后给了我Aborted(core dumped)。

我使用Valgrind运行代码。它在第105行和第106行说“无效免费”。 非常感谢帮助!

1 个答案:

答案 0 :(得分:2)

int *A1=(int *)malloc(halfsize*sizeof(int));
int *A2=(int *)malloc((size-halfsize)*sizeof(int)); 
A1=MergeSort(A, x, half);           //calling MergeSort on 1st half of array
A2=MergeSort(A, half+1, y);     //calling MergeSort on 2nd half of array

你正在分配A1,A2,然后覆盖指针(如果我用A正确地跟随递归)