Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive main() - why does it segfault?

Why does the following program segfault?

int main() { main(); }

Even though it is a recursion that does not end and is therefore invalid by definition, I don't see why it segfaults (gcc 4.4.3 and clang 1.5 (trunk)).

like image 258
user299831 Avatar asked Mar 23 '10 11:03

user299831


People also ask

Why does a segfault happen?

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.

How do you resolve a segfault?

It can be resolved by having a base condition to return from the recursive function. A pointer must point to valid memory before accessing it.

Is segfault a runtime error?

A segfault is one of several possible runtime errors; other runtime errors may include things like dividing by zero, domain error, range error, stack overflow, etc.

What causes PHP segmentation fault?

Because of the Memory Access Violation, a segmentation fault occurs. The error happens when a software tries to access a memory block that it is not permitted to access. To put it another way, you're approaching a memory location that isn't yours. In short, it's referred to as a segfault.


6 Answers

You get a stack overflow (!)

like image 170
Martin Wickman Avatar answered Sep 28 '22 08:09

Martin Wickman


Because every time it calls itself it allocates a little bit of stack space; eventually it runs out of stack space and segfaults. I'm a bit surprised it goes with a segfault, though; I would have expected (drum roll) stack overflow!

like image 29
T.J. Crowder Avatar answered Sep 28 '22 09:09

T.J. Crowder


int main() { main(); }

will cause a stack overflow.

But,

an optimized version (not debug mode) like this:

int main() {
   return main();
}

will transform the recursion in a tail-recursive call, aka an infinite loop!

like image 39
Nick Dandoulakis Avatar answered Sep 28 '22 08:09

Nick Dandoulakis


it is recurse without a base case, which causes a stack overflow

like image 38
Mihir Mehta Avatar answered Sep 28 '22 08:09

Mihir Mehta


It leads to stack overflow that is diagnosed as segfault on your system.

like image 30
sharptooth Avatar answered Sep 28 '22 08:09

sharptooth


Each function call add entires in stack and this entries will get removed from stack when function exit. Here we have recursive function call which doesn't have exit condition. So its a infinite number of function call one after another and this function never get exit and there entires never removed from the stack and it will lead to Stack overflow.

like image 44
Manish Avatar answered Sep 28 '22 08:09

Manish