-4

我有一个像这样的简单方法:

public int method(int a) 
{    
    if(// something)
    {
        methode(a); 
    }
    else return 0;
}

当调用深度增加时,Visual Studio 会引发stackoverflow 异常。

我怎么解决这个问题?有没有办法手动保存返回地址和本地数据并实现自定义堆栈?

我应该注意,我不想将我的方法更改为非递归类型。

4

5 回答 5

3

Yes, in C# (and probably in Java etc) there is a Stack<​T> class. For your method you can simply create a Stack and store the argument there. Iterate over the Stack until it's empty.

While this introduces an iterative loop, your algorithm is still recursive. (That is, depth first instead of breadth first)

Of course you need to make sure that your algorithm terminates eventually. This is just a way to increase stack space above what the operating system gives you. Windows allocates a certain amount of stack space for each process that suffices for most applications. If you need more, you can implement your own stack-like data structure on the heap. The heap is generally limited by the available RAM and the "bitness" of your application.

于 2013-10-07T07:23:26.623 回答
1

我怎么解决这个问题?有没有办法手动保存返回地址和本地数据并实现自定义堆栈?

递归方法应该有一个终止点,从那里返回结果。

于 2013-10-07T07:25:25.777 回答
0

You need to decrease the depth of recursion.

于 2013-10-07T07:24:07.600 回答
0
public int method(int a ){
//do stuff
  var something = ... //you have to make sure something turns false at some point
  if(something){ 
    method(a);
  }  
}
于 2013-10-07T07:31:15.173 回答
0

就像邓肯说的那样——“你必须确保某些事情在某个时候变成了假的”。

#define MAX 1000

#include <iostream>
using namespace std;



int methode(int a ){

    if(a>0 && a<MAX) return methode(a);

    return 0 ;

}// end

int main(void){


  methode(1);


  cout<<" \nPress any key to continue\n";
  cin.ignore();
  cin.get();

   return 0;
}
于 2013-10-07T07:40:29.013 回答