Amit Singh Tomar
Amit Singh Tomar

Reputation: 8610

Why below code gives segmentation fault problem?

I am trying to find the minimun number in an array using recursive function.but my code gives segemtation fault .

main()
{
    int a[5]={2,1,4,5,3};
    int n=1;
    fumi(a,n,a[0],5);
}

fumi(int a[],int n,int min,int t)
{
    if(n==t)
    {
        printf("%d",min);
    }
    if(a[n]<min)
    {
        min=a[n];
    }
    return(fumi(a,n+1,min,t));
}

Where am doing wrong and also main is not returning anything is not reason for segmentation fault.

Upvotes: 0

Views: 92

Answers (3)

phoxis
phoxis

Reputation: 61910

After executing

if(n==t)
{
    printf("%d",min);
}

It does not return, instead it goes on doing:

if(a[n]<min)
{
    min=a[n];
}

So when the base condition satisfies it does not return. Therefore the fumi function is always called recursively.

Two causes of segfault:

  1. As n goes beyond the max array length, an unallocated (illegal) memory access triggers it
  2. As the recursion does not return, we get a stack overflow, leads to a segmentation fault.

whichever occurs first.

Therefore the correction your code needs is to return when it encounters the base condition:

if(n==t)
{
    printf("%d",min);
    return;
}

Upvotes: 2

SoapBox
SoapBox

Reputation: 20609

Your code is very close to working. The reason it crashes is because the recursion never stops and goes on part the end of the array.

You correctly check for n == t and print out the result, but after that you don't return. The code keeps running on to infinity. Simply adding a return after the printf solves the problem:

void fumi(int a[],int n,int min,int t)
{
    if(n==t)
    {
        printf("%d",min);
        return; // stop recursing
    }
    if(a[n]<min)
    {
        min=a[n];
    }
    fumi(a,n+1,min,t);
}

Upvotes: 2

amit
amit

Reputation: 178421

you should also return after printf("%d",min); otherwise, you check if (a[t] < min), and a[t] was not allocated.

fumi(int a[],int n,int min,int t)
{
    if(n==t)
    {
        printf("%d",min);
        return; //This line was added
    }
    if(a[n]<min)
    {
        min=a[n];
    }
    return(fumi(a,n+1,min,t));
}

Upvotes: 4

Related Questions