Search code examples
c++visual-c++stack-overflow

Unhandled exception at 0x003714e9 in Quick.exe: 0xC00000FD: Stack overflow


This never happened to me and I got no idea how to fix it. It just says "Unhandled exception at 0x003714e9 in Quick.exe: 0xC00000FD: Stack overflow." then breaks and it highlights the bracket and shows an arrow next to it which I think it means that the error is located there. P.S. The bracket is in bold

#include<iostream>
using namespace std;

int partition(int data[], int left, int right)
**{**
    int pivot = data[left];
    while(true)
    {
        while(data[left] < pivot)
        { 
            left++;
        }
        while (data[right]>pivot)
        {
            //find smaller value than pivot from top array
            right--;
        }

        if(left < right)
        {
            //change pivot place
            int temp = data[right];
            data[right] = data[left];
            data[left] = temp;
        }
        else
        {
            return right;
        }
    }
}

void quickSort (int *data, int left, int right)
{

    if(left<right)
    {
        int cut = partition(data, left, right);
        if(cut>1)
        {
            quickSort(data, left, right);
        }
        if(cut+1<right)
        {
        quickSort(data, cut+1, right);
        }
    }
}

void quickSort(int *data, int length)
{
    quickSort(data, length-length, length-1);
}


void print_array(int array[], int size) //this function is to print the array after we finish sorting and we can use it before the sorting begin
{
    int j;
    for (j=0; j<size; j++)
    cout <<" "<< array[j]<<endl;

}//end of print_array

int main()
{
    const int size = 5;
    int arr[size]= {1, 17, 4, 6, 20};
    quickSort(arr, 0, size); 
    print_array(arr, size);
    system("pause");
    return 0;
}

Solution

  • I think the main problem lies in here:

    if(cut>1)
    {
        quickSort(data, left, right);
    }
    

    You are calling the function again and again between left/right. Maybe you should to use cut instead of right here? And actually, compare the cut with left then like you do with right ...

    The "corrupted stack" error after fixing the first issue is because the main() calls the quickSort function with wrong parameters - it should be either

    quickSort(arr, 0, size-1);
    

    or

    quickSort(arr, size); // the overload handling the -1
    

    Also, the length-length expression in the overloaded function is relatively convoluted way to write 0.

    You can also alter the code to actually take the size as right but then always start at right-1 (this is how std algorithms which take iterators usually work, allowing to pass end() which is after the last array item).