Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have written this Merge Sort program in C. It shows "Segmentation fault (core dumped)" after implementation of arrays

#include<stdio.h>
void mergesort();
void merge();
int main()
{
 int a[40],n;
 printf("\nEnter the number of elements:");
 scanf("%d",&n);
 printf("\nEnter the %d elements:",n);
 for(int i=0;i<n;i++)
 {
  scanf("%d",&a[i]);
 }
 mergesort(a,0,n-1); 
 printf("\nThe Sorted array is: ");
 for(int i=0;i<n;i++)
 {
  printf("%d ",a[i]);
 }
 return 0;
} 

void mergesort(int a[],int first,int last)
{
 int mid;
 if(first<last)
 {
  mid=(mid+last)/2;
  mergesort(a,first,mid);
  mergesort(a,mid+1,last);
  merge(a,first,mid,last);
 }
}

void merge(int a[],int first,int mid, int last)
{
 int b[50];
 int i,j,k;
 i=first;
 j=mid+1;
 k=first;
 while( i<=mid && j<=last) 
 {
  if(a[i]<=a[j])
    b[k++]=a[i++];
  else 
    b[k++]=a[j++];
 }
 if(i>mid)
 {
  while(j<=last)
   b[k++]=a[j++];
 }
 else
 {
  while(i<=mid)
   b[k++]=a[i++];
 }
  for(i=first;i<=last;i++)
  a[i]=b[i];
}

I have written this Merge Sort program in C. It shows "Segmentation fault (core dumped)" after implementation of arrays.
I don’t know what is the issue. So please help me out i have exam on the next day.
I get output like this

Enter the number of elements:5

Enter the 5 elements:1
2
3
5
4
Segmentation fault (core dumped)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The program has undefined behavior since you read mid when it’s uninitialized:

void mergesort(int a[], int first, int last) {
    int mid;
    if (first < last) {
        mid = (mid + last) / 2;
//             ^^^

You probably want:

        mid = (first + last) / 2;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading