Reputation: 107
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
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
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.
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;
}
Upvotes: 0