1

Here is the sample code which is giving segmentation fault error

#include<stdio.h>

void fun (); 

int main() { 
  fun ();
  return 0; 
} 

void fun () { 
   int i; 
   for (i=0;i <4;i++) { 
       fun (); 
       printf ("%d",i); 
   } 
}
Chris Travers
  • 25,424
  • 6
  • 65
  • 182
  • Why are you recursively calling `fun()` if it returns nothing? – bgfvdu3w Sep 30 '17 at 06:10
  • 3
    problem is name of this site :). You have infinitive recursion which leads to stack overflow. – Marek R Sep 30 '17 at 06:49
  • 1
    C != C++. Tag with the language you're actually using. That said, it looks like you're using C, becase you're including `stdio.h`. – tambre Sep 30 '17 at 06:58

2 Answers2

6

In the following code

void fun () { 
    int i; 
    for (i=0;i<4;i++) { 
        fun (); 
        printf ("%d",i); 
    } 
}

You are doing an infinite recursion. The function fun() calls itself and there is no exit condition for the recursion. So eventually the function stack will get exhausted and you will get segmentation fault.

J...S
  • 5,079
  • 1
  • 20
  • 35
Avishek Bhattacharya
  • 6,534
  • 3
  • 34
  • 53
1

This is because you are getting in an infinite recursion which leads to stack overflow. You have to add a base case for your recursive function to exit.

haccks
  • 104,019
  • 25
  • 176
  • 264