Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a limit on the stack size? [duplicate]

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?

like image 682
aufather Avatar asked Jul 11 '11 09:07

aufather


People also ask

Why is stack size limit?

If the stack would be allowed to grow arbitrarily large, these errors (like infinite recursion) would be caught very late, only after the operating systems resources are exhausted. This is prevented by setting an arbitrary limit to the stack size.

What is the stack size limit?

The stack size limit is the maximum size of the stack for a process, in units of 1024 bytes. The stack is a per-thread resource that has unlimited hard and soft limits. Set or display the CPU time limit. The CPU time limit is the maximum amount of CPU time (in seconds) allowed for the process.

Does a stack have a limit?

Yes, stack is always limited.

What determines how large the stack can grow?

The stack size might increase because: Each register push takes 4 bytes of memory in ARM, while in 16-bit or 8-bit each register push take 2 bytes or 1 byte. In ARM programming, local variables are often stored in the stack, while in some architectures local variables might be defined in a separate data memory area.


1 Answers

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.

like image 191
Mike Kwan Avatar answered Oct 20 '22 10:10

Mike Kwan