Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segfault with recursive function

Tags:

c

#include<stdio.h>

int recursive(int f,int g){
    static int a;;
    static int b;
    int c = 100;
    a = f;
    b = g;
    if(c != 105){
        a++;
        b++;
        c++;
        recursive(a,b);
    }

    printf("\n a : %d b : %d \n",a,b);

    return 0;
}


int main(){
    int a = 10;
    int b = 1;
    recursive(a,b);
}

The above example recursive program gives a segfault. Couldn't understand why the segfault happens as there is no pointers involved.

like image 822
Angus Avatar asked Nov 26 '22 23:11

Angus


2 Answers

You have infinite recursion in there. Because c is never equal to 105 (it's set to 100 every time you enter the function), the function will simply keep calling itself over and over, until you blow up the stack (exceed its capacity).

It boils down to something as simple as:

int blowUpStack (int a) {
    blowUpStack (a);
}
like image 160
paxdiablo Avatar answered Jan 02 '23 00:01

paxdiablo


The cause of the segfault is stack overflow :).

Stack is filling by function return adresses and local stacks until main stack pointer reach bound of stack segment.

like image 35
Spoonwalker Highwater Avatar answered Jan 02 '23 00:01

Spoonwalker Highwater