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