12

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?

Community
  • 1
  • 1
aufather
  • 651
  • 2
  • 7
  • 9
  • 3
    I read the top 4 answers in that thread. It gives a lot of useful information. But the focus is on differentiating stack from heap. It has been mentioned multiple times that a stack usually has a limit determined at the start of the the thread. My question is why is it so? The heap can grow at run time. Both stack and heap are part of the RAM and virtual memory of a process. Then why is the stack size limited? – aufather Jul 12 '11 at 06:42

1 Answers1

7

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.

Martin Jambon
  • 4,629
  • 2
  • 22
  • 28
Mike Kwan
  • 24,123
  • 12
  • 63
  • 96