Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was simply heapifying an array in C. But while running it's giving me segmentation fault(core dumped)... i have no idea where i am trying to access unallocated memory!!

#include<stdio.h>

int n;

int left(i)
{
    return (2*i);
}

int right(i)
{
    return (2*i + 1);
}


void min_heap(int a[],int i)
{
    int l=left(i);
    int r=right(i);
    int min;

    if((l<=n)&&(a[l]<=a[i])&&(a[l]<=a[r]))
    {
        min=a[l];
        a[i]=a[i]+a[l];
        a[l]=a[i]-a[l];
        a[i]=a[i]-a[l];
    }
    else if((r<=n)&&(a[r]<=a[i])&&(a[r]<=a[l]))
    {
        min=a[r];
        a[i]=a[i]+a[r];
        a[r]=a[i]-a[r];
        a[i]=a[i]-a[r];
    }

    min_heap(a,min);
}



int main()
{
    printf("The no is : ");
    scanf("%d",&n);
    int i,a[n+1];

    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }

    for(i=n/2;i>=1;i--)
    {
        min_heap(a,i);
    }

    for(i=1;i<=n;i++)
    {
        printf("%d",a[i]);
    }

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

You call min_heap(a,i) when i == n/2.

In this case, inside min_heap() the call to right() will return in effect:

(2 * (n/2) + 1)

When n is even that will result in a right index of n+1 and accessing a[r] (with r == n+1) is beyond the end of the array you've allocated.

I'm not sure if this is the reason for your segfault; I'd guess there may be other problems.

You should probably just step through a run with a debugger.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...