I get confused over when does the stack overflow error show up and when does the loop will be called infinite times in C !! Are both things same, if not then what's the difference between both scenarios. Please help.
5 Answers
A recursive call to a function that does not terminate will definitely lead to stack overflow. But not every stack overflow is caused by a recursive call that does not have a base case.
For example allocating storage for a huge local array will also very likely lead to stack overflow.
The following fails on my machine with a segmentation fault (due to my allocation exceeding the size of the stack I probably tried accessing memory that doesn't belong to my program):
#include <stdio.h>
int main()
{
int arr[1000 * 1000 * 100];
arr[99999999] = 0;
printf("%d\n", arr[99999999]);
return 0;
}
An infinite loop while something you cannot recover from will not automatically lead to a stack overflow (if you simply call for(;;) { int i = 1; } this by itself is not a stack overflow).
2 Comments
In c loop is called infinite when loop is never gonna stop. Stack is different thing. Stack memory is used by processor to temporary store data. Note that all local variables, arrays etc. are stored on stack. When you are storing too much variables on stack it may go beyond capacity of stack memory at that time stack is said to be overflow. Stack can be overflowed due to infinite loop also but not all the time. read: http://en.wikipedia.org/wiki/Stack_overflow
Comments
When you call into another function, you are using the stack -- you're placing local variables of the new function there, and a return address (generally speaking; this is architecture and implementation dependent). Do this too much and you run out of stack, overflowing it.
When you remain in a loop, you're not adding onto the stack.
2 Comments
Infinite Loop
Example:
while (1 + 1 == 2) { /* do something */ }
Symptoms:
Program freezes or doesn't stop running.
Explanation:
The condition is always true, so the body is executed again and again and again...
Stack Overflow
Example:
int stackOverflow(int x)
{
if (x == 0) return 1;
return x * stackOverflow(x - 1);
}
stackOverflow(4); // returns 24
stackOverflow(-1); // crashes with "Segmentation fault (core dumped)"
Symptoms:
Program crashes.
Explanation:
When a function is called, some space is allocated in a place called the stack for things such as local variables, the return address, and parameters. When the function returns this space is freed up. If before it finishes the function calls another function, more memory is allocated on the stack for the new function. If there are too many nested function calls (commonly caused by deep/infinite recursion) the stack runs out of space to store the information about all the currently invoked functions and you get a stack overflow.