using coroutines to solve stack over flow due to deep recursive function call

hi,

is there any one who has experience/advices on if and how we can solve the stack overflow issue due to deep recursive function call using coroutines? is using coroutine a correct direction to achieve have a relatively generic solution ?

thanks,
Alex
before you get exotic and weird, did you try a simple fix? What have you done so far?
A stack overflow can happen for one of two reasons:
1. There's a bug in the program, such that the base case is never hit or is not defined.
2. The recursive structure that needs to be walked is too deep.

#1 is solved by fixing the program.
#2 is solved by moving the state out of the stack and into a dynamic data structure.
Turning this:
1
2
3
4
5
6
7
8
9
10
void recursive(T foo){
    int var1;
    int var2;
    int var3;
    //...
    if (check(foo, var1, var2 /*...*/))
        return;
    bar(foo, var1, var2 /*...*/);
    recursive(foo);
}
Into this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void iterative(){
    struct Frame{
        T foo;
        int var1;
        int var2;
        int var3;
        //...
    };
    std::vector<Frame> stack;
    stack.emplace_back(); //Add initial frame
    while (true){
        auto &frame = stack.back();
        if (check(frame))
            break;
        stack.emplace_back(bar(frame));
    }
}
Can you solve the recursion problem using threads?

https://stackoverflow.com/questions/1934715/difference-between-a-coroutine-and-a-thread

You need to fix why you are blowing up the stack, using coroutines may or may not solve that problem. Only hide the reasons why things are going *KA-BLOOIE!*
Some other things to try:
- Increase the stack size. This is usually a linker option.
- Check for large data allocated on the stack in the recursive function. Replace it or put it on the heap or otherwise get it out of the stack.

Topic archived. No new replies allowed.