Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why infinite recursion leads to seg fault

Tags:

c++

c

linux

Why infinite recursion leads to seg fault ? Why stack overflow leads to seg fault. I am looking for detailed explanation.

int f()
{
  f();
}

int main()
{
  f();
}
like image 566
Pqr Avatar asked Jun 03 '10 10:06

Pqr


People also ask

What does infinite recursion cause?

If a recursion never reaches a base case, it will go on making recursive calls forever and the program will never terminate. This is known as infinite recursion, and it is generally not considered a good idea. In most programming environments, a program with an infinite recursion will not really run forever.

How is segfault caused?

Overview. A segmentation fault (aka segfault) is a common condition that causes programs to crash; they are often associated with a file named core . Segfaults are caused by a program trying to read or write an illegal memory location.

Can recursion cause segmentation fault?

A seg fault occurs when the call stack gets too big - i.e. too many levels of recursion. In your case, this means the condition (new - old) < accurate will always evaluate to false - well, maybe not always, but enough times to bloat the call stack.

What leads to infinite recursion in Python?

Infinite Recursion occurs when the recursion does not terminate after a finite number of recursive calls.


2 Answers

Every time you call f(), you increase the size of the stack - that's where the return address is stored so the program knows where to go to when f() completes. As you never exit f(), the stack is going to increase by at least one return address each call. Once the stack segment is full up, you get a segfault error. You'll get similar results in every OS.

like image 112
Skizz Avatar answered Oct 29 '22 16:10

Skizz


Segmentation fault is a condition when your program tries to access a memory location that it is not allowed to access. Infinite recursion causes your stack to grow. And grow. And grow. Eventually it will grow to a point when it will spill into an area of memory that your program is forbidden to access by the operating system. That's when you get the segmentation fault.

like image 44
Dima Avatar answered Oct 29 '22 15:10

Dima