# Counting Sort : Unable to execute , segmentation fault (core dumped) if i'll add to line to print the sorted array.

#include<stdio.h>

void counting_sort(int a[], int r[]);
//void printarray(int a[]);
int main()
{
int a[55],i,n=7,j,k,l,range=5,r[33];
printf(" Enter the total number for sorting");
scanf("%d", &n);
for(int i=0;i<7;i++)
{
printf(“Enter the number for sorting\n”);
scanf("%d", &a[i]);
}
for(j=0;j<range;j++)
{
printf(“Enter the number for range\n”);
scanf("%d",&r[j]);
}

``````    counting_sort(a,r);
//printarray(a);
``````

}
void counting_sort(int a[33], int r[33])
{
int key, o[33], count, sum, b[77];
for(int i=0;i<5;i++)
{
count=0;
key=r[i];
for(int j=0;j<7;j++)
{
if(a[j]==key)
count++;
}
b[i]=count;
b[i]= b[i]+sum;
sum=b[i];
//b[i+1]= b[i]+b[i+1];
printf(" %d after adding is %d \n",r[i], b[i]);
}
for(int k=0;k<5;k++)
{
while(b[k]>0)
{
b[k]–;
o[b[k]]=r[k];
}
}
for(int l=0;l<7;l++)
printf("%d sorted array", o[l]);

``    }``

In variable declaration, n = 7;

Then, why are you using this statement?

“scanf(”%d", &n);"

No need to use both of them.

Also provide the test case for which “Unable to execute , segmentation fault (core dumped)” is shown.

Hey @rajni,

The problem lies in the fact that your program is hardcoded and you must be checking it for various inputs where A[i] doesn’t exist.

Change the for loops where you have taken 7 to n and then check if that also doesn’t work comment below I’ll try to help!

Hope this helps!

(If this doesn’t work go to this link where you can find code implemented with the explanation.)

Hi,

After replacing 7 to n in loops, there is no segmentation fault but output is not in sorted numbers.

The main problem lies in the following lines of the program.
for(int k=0;k<5;k++)
{
while(b[k]>0)
{
b[k]–;
o[b[k]]=r[k];
}
}
for(int l=0;l<n;l++)
printf("%d sorted array\n", o[l]);