Home > Enterprise >  Why is there segmentation fault in this merge sort?
Why is there segmentation fault in this merge sort?

Time:06-23

I compiled this code on different compilers, but all of them gave runtime error. Can someone tell me what's wrong with this code?

void merge(int *str, int beg, int mid, int end) {
    int *arr = new int[end - beg   1];
    int k = 0;
    int i = beg;
    int j = mid   1;
    while (i <= mid && j <= end) {
        if (str[i] < str[j]) {
            arr[k] = str[i];
            i  ;
            k  ;
        } else {
            arr[k] = str[j];
            j  ;
            k  ;
        }
    }
    while (i <= mid) {
        arr[k] = str[i];
        i  ;
        k  ;
    }
    while (j <= end) {
        arr[k] = str[j];
        //here i got buffer overrun while writing to arr
        j  ;
        k  ;
    }
    for (i = beg; i <= end; i  ) {
        str[i] = arr[i - beg];
    }
    delete[] arr;
}

void merge_sort(int *str, int beg, int end) {
    
    if (beg >= end)
        return;

    int mid = (end - beg) / 2;
    merge_sort(str, beg, mid);
    merge_sort(str, mid   1, end);
    merge(str, beg, mid, end);
}

This code is almost same as I found on Sanfoundry, but that one is working but mine got some errors.

CodePudding user response:

Your computation of the mid point in merge_sort is incorrect: instead of int mid = (end - beg) / 2; you should write:

    int mid = beg   (end - beg) / 2;
  • Related