Why are stack overflows still a problem?

前端 未结 11 1396
故里飘歌
故里飘歌 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 11:02

    I am going to summarize the arguments in the answers so far because I find no answer covering this topic good enough.

    Static stack investigation

    Motivation

    Not everyone needs it.

    • Most algorithms do not use deep recursion or a lot of threads, thus not a lot of people need dynamic stacks.
    • Dynamic stack would make an infinite-recursion stack overflow, which is an easy mistake to make, harder to diagnose. (memory overflow, while being as deadly as a stack overflow to the current process, is hazardous for other processess as well)
    • Every recursive algorithm can be emulated with a similar iterative one.

    Implementation difficulties

    Dynamic stack implementation turns out to be not as straightforward as it seems.

    • Stack resizing alone is not enough unless you have unlimited address space. You will sometimes need to relocate the stack as well.
    • Stack relocation would require updates for all the pointers to the data structures allocated on the stack. While it is straightforward (at least in managed languages) for the data in memory, there is no easy way to do the same for data in the CPU registers of the thread.
    • Some CPUs (microcontrollers in particular) implement the stack directly on hardware, separate from the main memory.

    Existing implementations

    There are some languages or runtime libraries that already have the dynamic stack feature or something similar to it.

    • Some runtime libraries (which?) do not pre-commit the entire block of memory allocated for stack. This can alleviate the problem, expecially for 64-bit systems, but not completely eliminate it.
    • Ira Baxter told us about PARLANSE, a language specifically designed for dealing with complex data structures with high degree of parallelism. It uses small heap-allocated "grains" of work instead of stack.
    • fuzzy lolipop told us that "Properly written Erlang doesn't have stackoverflows!"
    • Google Go programming language is said to have a dynamic stack. (a link would be nice)

    I would like to see more examples here.

    I hope I didn't forget any important pieces of information on this subject. Making this a community wiki so that anyone can add new information.

提交回复
热议问题