Segfault with recursive function

#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);
}

In the above example, a recursive program gives segfault. It was not possible to understand why segfault happens because there are no pointers.

+4
source share
6 answers

Since your variable is cnot static, you will be calling again and again recursive, always reinitializing it with 100, so your program will never stop and eventually crash due to. I suppose you meant to cincrease every time a function is called recursively? Then you need to change its declaration:

static int c = 100;

(What some others mentioned: “you need a base case” and you will get it if it cis static.)

100, () .

+4

. c 105 ( 100 , ), , ( ).

- :

int blowUpStack (int a) {
    blowUpStack (a);
}
+11

segfault :).

, .

+8

c 101, , , reset 100, .

+7

Segfaults . , segfault - , , , . Boom.

, : c - , .

+7

Seg Fault , , . , .

In this question, your recursion never ends, because the function has no base argument to exit. Therefore, endless recursive calls will lead to a stack overflow, and therefore, your program can access an unallocated memory address.

In this case, you may want to ckeep its value in a previous call, so you need to declare it static.

+3
source

All Articles