开发者

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 a开发者_如何学JAVAnything is not reason for segmentation fault.


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


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


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜