c - C 中使用 malloc : malloc. c:2451:sYSMALLOc "Assertion Failed"时出错

标签 c pointers malloc

我是 C 初学者,遇到内存分配问题。我查了相关讨论。我可能应该使用 Valgrind,但在我学习如何使用它之前,我将问题发布在这里。

这是我制作的合并排序代码的链接。 http://ideone.com/utEzoq

但是,主要问题似乎出在以下部分:

void main()
{
     MergeSort(list, 0, n-1) //calling function on pointer to array of integers
}

int *MergeSort(int *A, int x, int y) //declaration
{
if(x==y)
{
    return A;
}

else
{
    int size=1+y-x;
    int half=(x+y)/2;

    MergeSort(A, x, half);  
    MergeSort(A, half+1, y);    


    int *C;
    C=(int *)malloc(size*sizeof(int));
    int j=x;
    int k=half;
    int i=0;


    while((j<=half)||(k<=y))            
    {
        if(A[j]<=A[k])
        {
            C[i]=A[j];
            j++;
        }
        else
        {
            C[i]=A[k];
            k++;
        }
        i++;
    }


    if(j==(half+1))
    {
        while(i<size)
        {
            C[i]=A[k];
            i++;
            k++;
        }
    }
    else if(k==(y+1))
    {
        while(i<size)
        {
            C[i]=A[j];
            i++;
            j++;
        }
    }

    return C;
}

然而,不同类型的输入都会出现错误。当我输入一个反向排序和排序的数组时,它按照输入的顺序返回输出。随机数给出了 malloc“断言失败”错误。

非常感谢您的帮助。

最佳答案

你的问题

void main()

int main()

int k=half;

int k=half+1;

while((j<=half)||(k<=y)) 

while((j<=half)&&(k<=y))

return C;

for(i=0;i<size;++i){
    A[x+i]=C[i];
}
free(C);
return A;

关于c - C 中使用 malloc : malloc. c:2451:sYSMALLOc "Assertion Failed"时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21943673/

相关文章:

c - C 中的运算符结合性特别是前缀和后缀递增和递减

c - 在 Bison 出错后释放留在堆栈上的指针

C编程: How do I use realloc in this program?

c - C 中带有++ 运算符的语句的短路评估

c - 从文本文件读取会跳过第一行

c - K&R 的 atof 实现有什么问题?

c++ - 在 C++ 中重新分配指针的正确方法

c - 是否有一个 malloc 实现在它自己的堆之外进行簿记?

c - 从文件中存储多种类型的数据

c - C中整数指针数组的静态初始化错误