开发者

Resolving StackOverFlowException in C++

I am trying to write a program for selection sort of the elements an array in C++ (VS2010) using recursion. The program works without any issues for for smaller arrays where the size of the array is less than 10 when I increase the size of the array to 10000 I am facing stackoverflow exception. How do I go about resolving this?

Thank you for the answers so far. My idea is not to sort the array but to sort a large array using recursion and the hit a stackoverflow exception. My main idea behind this exercise is to learn ways to resolve the stackoverflow exception rather开发者_如何学JAVA than sorting the array.

selectionSortRecursive(int a[], int startindex, int endindex)
{
    if (startindex<endindex)
    {
        int s = startindex;
        for (int index=startindex+1;index<endindex;index++)
        {
            if (a[s]>a[index])
                s=index;
        }
        if (s>startindex)
        {
            a[s]=a[startindex]+a[s];
            a[startindex]=a[s]-a[startindex];
            a[s]=a[s]-a[startindex];
        }
        selectionSortRecursive(a, startindex+1, endindex);
    }

}


Either increase the size of the stack (which can be done with the STACK linker option) or -- and this is a much better option -- improve or replace your algorithm. It sounds like a recursive algorithm may not be suitable for the kind of data you need to process, but maybe you can improve things by using fewer local variables and/or parameters in each method invocation, to make the stack frames smaller.


You are either using a great deal of local storage or your recursive algorithms explodes memory usage by subsequent calls. In either case probably an iterative solution would solve your problems.


Local variables, as you may know, are kept on the stack.

When a function recurses, local variables from each call remain on the stack for as long as their respective functions execute. If you recurse too much, the build-up will be too great and you will likely end up with a stack overflow exception, like you're getting, or a segmentation fault, where the stack overflows into protected memory.

This is fundamental, and there is no way around it other than to increase your available memory or to rewrite your function to be iterative.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜