Why infinite recursion leads to seg fault

后端 未结 8 2218
长情又很酷
长情又很酷 2020-12-04 01:42

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()
{
           


        
8条回答
  •  鱼传尺愫
    2020-12-04 02:11

    It's essentially the same principle as a buffer overflow; the OS allocates a fixed amount of memory for the stack, and when you run out (stack overflow) you get undefined behavior, which in this context means a SIGSEGV.

    The basic idea:

    int stack[A_LOT];
    int rsp=0;
    
    void call(Func_p fn)
        {
        stack[rsp++] = rip;
        rip = fn;
        }
    
    void retn()
        {
        rip = stack[--rsp];
        }
    
    /*recurse*/
    for(;;){call(somefunc);}
    

    eventually rsp moves past the end of the stack and you try to put the next return address in unallocated storage and your program barfs. Obviously real systems are a lot more complicated than that, but that could (and has) take up several large books.

提交回复
热议问题