简体   繁体   中英

Merge Sort Program crashes with "Exited with code: 3221225477"

I'm trying to write the Merge Sort Algorithm code with dynamic memory allocation using Malloc . Actually, this malloc is used for memory allocation for the auxiliary array used in Merge() . Everything was okay when I was using a static array for B But now when I am using Malloc it's throwing an unknown error as mentioned above. Thanks for any help you can give!

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

void printArray(int *A, int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d ", A[i]);
    }
    printf("\n");
}

void merge(int A[], int mid, int low, int high)
{
    int i, j, k;
    int* B = (int *)malloc((high-low+1)*sizeof(int));
    i = low;
    j = mid + 1;
    k = low;

    while (i <= mid && j <= high)
    {
        if (A[i] < A[j])
        {
            B[k] = A[i];
            i++;
            k++;
        }
        else
        {
            B[k] = A[j];
            j++;
            k++;
        }
    }
    while (i <= mid)
    {
        B[k] = A[i];
        k++;
        i++;
    }
    while (j <= high)
    {
        B[k] = A[j];
        k++;
        j++;
    }
    for (int i = low; i <= high; i++)
    {
        A[i] = B[i];
    }

    free(B);
    
}

void mergeSort(int A[], int low, int high){
    int mid; 
    if(low<high){
        mid = (low + high) /2;
        mergeSort(A, low, mid);
        mergeSort(A, mid+1, high);
        merge(A, mid, low, high);
    }
}

int main()
{
    // int A[] = {9, 14, 4, 8, 7, 5, 6};
    int A[] = {9, 1, 4, 14, 4, 15, 6};
    int n = 7;
    printArray(A, n);
    mergeSort(A, 0, 6);
    printArray(A, n);
    return 0;
}

错误信息

Here, after allocating the memory of high - low + 1 ints to B, the indexing of B will start with 0 and end at high - low + 1 . So, every index of B should be between these limits.

So, you should replace the expressions B[i] and B[k] with B[i - low] and B[k - low] respectively.

Change B[i] to B[i-low] and B[j] to V[j-low]

Exchange B[i] to B[i-low] and B[j] to V[j-low]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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