Search code examples
c++algorithmsortingmergesort

Merge sort - stack corruption error


I'm writing a basic merge sort code in C++. I'm getting stack corruption exception for variable b, when I run the below code in function merge(). I just can't figure out what am I doing wrong. Any help is highly appreciated !!

Here's my code:

template <class T>
class mSort 
{
    void mergeSort(T *a, int low, int high);
    void merge(T *a, int low, int mid, int high);
public:
    mSort(T* a, int size);
};

template<class T>
mSort<T>::mSort(T *a, int size)
{
    mergeSort(a, 0, size);
}
template<class T>
void mSort<T>::mergeSort(T *a, int low, int high)
{
    int m;
    if (low < high)
    {
        m = (low + high) / 2;
        //printf("mergeSort:low[%d], mid [%d], high [%d]\n", low, m, high);
        mergeSort(a, low, m);
        mergeSort(a, m+1, high);
        merge(a, low, m, high);
    }
}

template<class T>
void mSort<T>::merge(T *a, int low, int mid, int high)
{
    int b[20];
    int i = low, j = mid + 1, k = 0;

    while (i <= mid && j <= high) {
        if (a[i] <= a[j])
            b[k++] = a[i++];
        else
            b[k++] = a[j++];
    }
    while (i <= mid)
        b[k++] = a[i++];

    while (j <= high)
        b[k++] = a[j++];

    k--;
    while (k >= 0) {
        a[low + k] = b[k];
        k--;
    }
}

Input array : int a[20];

#define prep_intput_array(a,n)\
for (int i = 0; i < n; i++)\
{\
    a[i] = rand() % 65535;\
}\

calling the merge sort routine like this :

mSort<int> m1(a, 20);

Code is based on the merge sort in this link


Solution

  • high is passed with highest index in the array which is size-1 but you have passed size which is more than highest index in the array hence you might be getting an error.