Search code examples
csortingsegmentation-faultcounting-sort

I have seg fault in my counting sort


Here is my code, for some reason I have to use unsigned long. The gdb tells me that I have seg fault. Can one can help me? I could not find it by myself. The most interesting thing is that if I change the type to int from unsigned long, there is no seg fault.

Code is here:

#include <stdio.h>
int counting_Sort (unsigned long ary[], unsigned long array_size,unsigned long max){


    unsigned long counting[max+1];
    unsigned long j;
    for(j=0;j<max+1;j++){
        counting[j]=0;//initize to zero
    }

      unsigned long i;
    for(i=0;i<array_size;i++){
        counting[ary[i]]++;
    }

    unsigned long q;
    for(q=1;q<max+1;q++){
       counting[q]=counting[q-1]+counting[q];
    }

    for(q=0;q<max+1;q++){
       counting[q]=counting[q]-1;
    }

    unsigned long  outputAry[array_size];
    unsigned long  d;
    for(d=(array_size-1); d>=0;d--){
         outputAry[counting[ary[d]]]=ary[d];// SEG FAULT IS HERE
         counting[ary[d]]--;//AND HERE

    }
    unsigned long  m;
    //for(m=0; m<array_size;m++){
      // printf("%lu\n",outputAry[m]);
   // }
    return 0;
}        




int main(){
    unsigned long  array[7]={2,6,4,0,1,7,9};
    printf("before sorting the order is: \n");
    unsigned long  i;
    for(i=0;i<7;i++){
        printf("%lu\n",array[i]);
    }

    printf("after sorting, the new order is: \n");
    counting_Sort(array,7,9);


    getchar();
    return 0;

}

Solution

  • You've found the place, just not the reason.

    unsigned long  d;
    for(d=(array_size-1); d>=0;d--){
    

    d is an unsigned integer, which means d>=0 is always true. The loop never ends, and that's the reason of segmentation fault.

    One way is to change d to a singed type:

    int d;
    

    But if that's not what you want, change the for loop to:

    for (d = 0; d <= array_size - 1; d++){