Question

I have this heapsort program which run on Windows, but is giving segmentation fault on ubuntu 14.04.

#include<stdio.h>
#define N 5000
int arr[N];
int size=N-1;
int parent(int i)
{
    return (i-1)/2;
}
 int lchild(int i)
{
     return 2*i+1;
}
int rchild(int i)
{
     return 2*i+2;
}
void maxheapify(int arr[],int i)
{
     int larg,t;
     int l=lchild(i);
     int r=rchild(i);
     if(arr[l]>arr[i] && l<=size)
         larg=l;
     else
         larg=i;
     if(arr[r]>arr[larg] && r<=size)
         larg=r;
         if(larg!=i)
         {
             t=arr[larg];
             arr[larg]=arr[i];
             arr[i]=t;
             maxheapify(arr,larg);
         }  
 }
 void buildmaxh(int arr[])
 {
     int i;
     for(i=N/2-1;i>=0;i--)
     maxheapify(arr,i);
 }
 void heapsort(int arr[])
 {
     int i,t;
     buildmaxh(arr);
     size--;
     for(i=N-1;i>0;i--,size--)
     {
         t=arr[0];
         arr[0]=arr[i];
         arr[i]=t;
         maxheapify(arr,0);
     }
}
int main()
{
     srand(time(NULL));
     int i;
     for( i=0;i<N;i++)
          arr[i]=rand()%101;
     heapsort(arr);
     printf("done\n\n");
     return 0;
 }

What is the source of error? How can I remove this error?

I tried debugging the code using gdb as explained here. But I can't compile the program as described in the answer. I used command gcc myfile.c -ggdb myfile. Also,using command: gcc myfile.c -o myfile I compiled the program successfully, which gave me segmentation error. What am I doing wrong? Thanks.

Was it helpful?

Solution

The error occurs in maxheapify when you check which of the children is larg:

if (arr[l]>arr[i] && l<=size) ...

You've got the checks the wrong way round. When you read arr[l], l might be out of bounds, which is a segmentation violation. If you check the bounds first like this:

if (l<=size  && arr[l]>arr[i]) ...

the read access won't happen if l is out of bounds. (Remember that the && and || operators short-circuit the evaluation: In a && b, b is never checked if a is already false, because there's no way the whole expression can be true.)

The same goes for the check of arr[r] some lines after that.

Also, please include <stdlib.h> and <time.h>; they are needed for your randomisation code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top