text: Q:
  
  Segmentation Fault in Mergesort While assigning an array - c
  
  I have written a Merge Sort program in c but getting a segmentation fault. After trying to debug my code i got to know the particular line in which i am getting the error but i wanted to know what is the reason??
  Here is my code:
  void Mergesort(struct record r[],int n)
  {
      int k;
      if(n>1)
      {
          int i,j;
          struct record r1[n/2];
          struct record r2[n/2];
          for(i=0,j=n/2;i<n/2,j<n;i++,j++)
          {
              r1[i]=r[i];
              r2[i]=r[j]; // this is the line where i am getting the error.
          }
          Mergesort(r1,n/2);
          Mergesort(r2,n/2);
          r=Merge(r1,r2,r,n);
      }
  
  }
  
  struct record * Merge(struct record r1[],struct record r2[],struct record r[],int n)
  {
      int i=0,j=0,k=0;
      while(i<n/2 && j<n/2)
      {
          if (strcmp(r1[i].a,r2[j].a)<=0)
          {
              r[k]=r1[i];
              i=i+1;
          }
          else
          {
              r[k]=r2[j];
              j=j+1;
          }
          k=k+1;
      }
      if(i==n/2)
      {
          for(j;j<n/2,k<n;j++,k++)
          {
              r[k]=r2[j];
          }
  
      }
      else
      {
          for(i;i<n/2,k<n;i++,k++)
          {
              r[k]=r1[i];
          }
      }
      return r;
  }
  
  One more thing : I am getting segmentation fault only when the no. of entries which i want to sort are not a power of 2. The code is running properly for entries such as 2,4,8,16.
  
  A:
  
  The error is because when you have odd number of entries, you under allocate. 
  Example:
  when n = 7, n/2 is 3. so you have both r1 and r2 of size 3 for a total of 6. In the for loop, the i is less than 3 (i.e, 0,1,2) and j has initial value 3 and max value 6 (so 3,4,5,6). so j needs 4 but r2 has only memory for 3 elements. So, it crashes.
  It does not happen for powers of 2, because even when you divided the array by 2, they still remain powers of 2 and even except for 1. When there is only one element, you don't have to do anything. 
  I think you need to allocate n - n/2 for r2.
  
  