Search code examples
cpointersalloc

program hangs after inputting array


#include<stdio.h>
#include<conio.h>
//#include<alloc.h>

int* mergeSort(int*,int);
int* merge(int*,int*,int);

void main()
{
  int n;int i=0;
  int *a,*b;

  scanf("%d",&n);
  a=(int)malloc(n*sizeof(int));
  for(;i<n;i++)
     scanf("%d",&a[i]);

  b=mergeSort(a,n);
  for(i=0;i<n;i++)
     printf("%d ",b[i]);

}

int* mergeSort(int *b,int n)
{
  int temp,*s;

  if(n>2)
  {
     mergeSort(b,n/2);
     mergeSort(b+n/2,n-n/2);
     s=merge(b,b+n/2,n);

     return s;
  }
  else if(n==2)
  {
     if(b[0]>b[1])
     {
         temp=b[0];
         b[0]=b[1];
         b[1]=temp; 
     }
     return;
  }
}

int* merge(int* a,int* c,int n)
{
  int i=0,j=0,k=0,
  int* x;

  while( (j ! =n/2) && (k != (n-n/2)) && (i < n))
  {
       if(a[j]<c[k])
       {
             x[i]=a[j];
             j++; 
             i++;
       }
       else
       {
             x[i]=c[k];
             k++;
             i++;
       }
   }
   for( ; j<n/2; j++,i++)
      x[i]=a[j];

   for( ; k < (n-n/2); k++,i++)
      x[i]=c[k];

   return x;
}

when i run this code,it hangs after inputting all the elements of the array in first for loop. Please help me, how can i correct it to make it work successfully? it hangs on calling the mergeSort function from main() function.


Solution

  • it hangs after inputting all the elements of the array in first for loop.

    hangs? Are you sure... that's pretty good considering your merge code declares a pointer to an int:

    int *x;
    

    and never initializes it, then tries to jump to an offset (i) past it:

    x[i]=a[j];
    

    Change your code to this:

    int *x = malloc(n * sizeof(int));
    

    and it should stop crashing/hanging whatever.

    FYI, whenever you malloc() you should free() right now you have memory leaks.