Why are stack overflows still a problem?

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

    1) In order to resize stacks, you have to be able to move memory around, meaning that pointers to anything on a stack can become invalid after a stack resize. Yes, you can use another level of indirection to solve this problem, but remember that the stack is used very, very frequently.

    2) It significantly makes things more complicated. Push/pop operations on stacks usually work simply by doing some pointer arithmetic on a CPU register. That's why allocation on a stack is faster than allocation on the free-store.

    3) Some CPUs (microcontrollers in particular) implement the stack directly on hardware, separate from the main memory.

    Also, you can set the size of a stack of a thread when you create a new thread using beginthread(), so if you find that the extra stack space is unnecessary, you can set the stack size accordingly.

    From my experience, stack overflows are usually caused by infinite recursions or recursive functions that allocate huge arrays on the stack. According to MSDN, the default stack size set by the linker is 1MB (the header of executable files can set their own default), which seems to be more than big enough for a majority of cases.

    The fixed-stack mechanism works well enough for a majority of applications, so there's no real need to go change it. If it doesn't, you can always roll out your own stack.

提交回复
热议问题