Search code examples
memoryheap-memorystack-overflow

How do stack overflows occur if the stack can grow?


A stack overflow error occurs when a program tries to use more memory in the stack that has been allocated to the stack. But I heard that the stack can grow up or down. If it can grow when it needs memory, then how do stack overflow errors occur?

Does this mean that heap overflow errors exist?


Solution

  • Typically an application has a set maximum amount of stack space. The stack can grow up to that maximum. When the application is started, the operating system allocates a small amount of space for its stack. As needs warrant, the operating system can allocate more space for the application's stack. But it can't ever go beyond the maximum.

    So why not just let it grow, unbounded? Because no computer has infinite memory. If we placed no restriction on the amount of stack space an application can use, then a misbehaving application would run until it allocated all the memory available. It wouldn't take long to effectively lock up the machine, preventing any work from being done.

    So we place limits on stack space. The default is more than enough for most programs. If you determine that your application needs more than the default stack space, then you can specify a larger stack at build time.