Why are stack overflows still a problem?

前端 未结 11 1460
故里飘歌
故里飘歌 2020-12-25 10:22

This question is mystifying me for years and considering this site\'s name, this is the place to ask.

Why do we, programmers, still have this StackOverflow

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-25 10:54

    Why do we, programmers, still have this StackOverflow problem?

    Stack of fixed size is easy to implement, and is acceptable for 99% of programs. "stack overflow" is a minor problem, that is somewhat rare. So there is no real reason to change things. Also, it is not a language problem, it is more related to platform/processor design, so you'll have to deal with it.

    There is no way to write a recursive algorithm unless you are absolutely sure that the depth of recursion is tiny. Linear memory complexity of the recursive algorithm is often unacceptable.

    Now this is incorrect. In recursive algorithm you can (almost?) always replace actual recursive call with some kind of container - list, std::vector, stack, array, FIFO queue, etc, that will act like stack. Calculation will "pop" arguments from the end of the container, and push new arguments into either end or beginning of container. Normally, the only limit on size of such container is total amount of RAM.

    Here is a crude C++ example:

    #include 
    #include 
    
    size_t fac(size_t arg){
        std::deque v;
        v.push_back(arg);
        while (v.back() > 2)
            v.push_back(v.back() - 1);
        size_t result = 1;
        for (size_t i = 0; i < v.size(); i++)
            result *= v[i];
        return result;
    }
    
    int main(int argc, char** argv){
        int arg = 12;
        std::cout << " fac of " << arg << " is " << fac(arg) << std::endl;
        return 0;
    }
    

    Less elegant than recursion, but no stackoverflow problem. Technically, we're "emulating" recursion in this case. You can think that stackoverflow is a hardware limitation you have to deal with.

提交回复
热议问题