Why is there a limit on the stack size?
Possible Duplicate:
What and where are the stack and heap
My installation of Ubuntu has a default stack size limit of 8 MB. But I am curious as to why we need to restrict a user program's stack size. The same program can use all of its 4 GB (for a 32 bit program) addressable space via malloc/mmap etc. So why do we need a stack size limit? Why can't the stack grow till it almost meets the heap?
In fact the stack does grow more and more. It doesn't need to start very big since in the general case, it doesn't need to be very big. Having it as very big results in a wasteful memory footprint.
I'm not 100% sure as to how the stack is implemented on Linux but on Windows, a large amount of space is reserved for the stack. This amount can be set in compiler options (you may want a larger stack for deeply recursive programs). At runtime, the stack can be extended dynamically via a guard page system. At the end of the stack there is a guard page which when hit will extend the stack by an extra page and push the guard page forward by one.
Stack probing is another interesting and related concept. So your question of 'why can't the stack grow till it almost meets the heap?' The stack does grow but since most of the time having a huge stack is likely an undesired side-effect of a bug, the reserved size will not be huge (although this is settable).
This article is very interesting and relevant to your question.
链接地址: http://www.djcxy.com/p/2268.html上一篇: C ++中的Oridinary(自动)变量使用堆栈还是堆?
下一篇: 为什么堆栈大小有限制?