The stack memory
is used to store local variables and function call, while heap memory
is used to store objects.If there is no memory left in stack for storing function call or local variable,then it leads to stackoverflow error.Common eg for this would be recursive function because it stores information about the function (information includes where it left or called itself again) in stack.
If you have a function like:
<code>int foo()
{
// more stuff
foo();
}</code>
Then foo() will keep calling itself, getting deeper and deeper, and when the space used to keep track of what functions you're in is filled up, you get the stack overflow error.
In more detail:
Usually there's a one stack for a process(program in the running state).That stack tends to be a fixed memory range somewhere in the memory, therefore it's limited how much it can contain values.
If the stack is empty you can't pop, if you do you'll get stack underflow error.
If the stack is full you can't push, if you do you'll get stack overflow error.
So stack overflow appears where you allocate too much into the stack.