Timmy
Timmy

Reputation: 107

Recursion segmentation fault and StackGuard

Lets say I have a function that all it does is calling itself without any termination.

myFunction(){
    myFunction()
}

if I run a program containing this function, I will eventually get a segmentation fault. Why does this happen? Running out of stack space?

Also, can StackGuard protect against this fault? Why or why not?

Upvotes: 1

Views: 134

Answers (2)

user7101157
user7101157

Reputation:

Each time you call a function it will cause a new stack frame to be created in memory for that function call. This stack disappears when the function returns. As your function does not return and keeps calling new calls it will keep creating stack frames which means eventually you run out of memory to keep those stack frames.

Upvotes: 0

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

As the recursion is infinite, and for each call the return address and base pointer (frame pointer) at least are pushed onto the stack, you will eventually run out of stack space, or more generally, run out of memory, as memory is a finite resource.

Nothing can guard against this because it is the programmer who "designed" this infinite recursion. What would you expect "protect against this fault"? As I said it is not a fault as it is the program's design. You just run out of a finite resource, causing the OS to abort the program.


EDIT: the following is an example of intercepting the seg fault (untested, based on VC2008 doc):

jmp_buf home;

void myFunction(void)
{
    myFunction();
}
void SegvHandler(int signal)
{
    longjmp(home);
}
int main(void)
{
    signal(SIGSEGV, SegvHandler);
    if (setjmp(home)) {
        printf("Oops...\n)
        return 1;
    }
    myFunction();
    return 0;
}


TEST: after testing in VC2008, it appears not to be possible to catch this error. The reason seems to be/could be that: first the stack overflow occurrs, and now there is no more stack space to call another function, the signal handler.

Upvotes: 0

Related Questions