我不知道为什么这会导致细分错误?

时间:2019-04-30 19:55:28

标签: c++ segmentation-fault

最初,我收到“细分错误:11”错误,当我在if (l < r)中包含mergeSort()时,错误停止了(太好了!)。但是,如果您查看main(),则l < r总是这样。因此,我不知道为什么包括if语句可修复分段错误。如果有人可以解释这一点,那就太好了。谢谢!

// Merge two subarrays of arr[] in order
// First subarray arr[l..,m]
// Second subarray arr[m+1,r]
void merge(int arr[], int l, int m, int r) {

  // size of first and second subarrays
  int size1 = m - l + 1;
  int size2 = r - m;

  // create two temp arrays for first and second subarrays
  int leftArray[size1];
  int rightArray[size2];

  // copy the data from subarrys to temp subarrays
  for(int i=0; i < size1; i++) {
    leftArray[i] = arr[l+i];
  }
  for(int j=0; j < size2; j++) {
    rightArray[j] = arr[m+1+j];
  }

  // merge temp arrays back into arr[1...r]
  int i = 0;  // intial index of first subarray
  int j = 0;  // intial index of second subarray
  int k = l;  // initial index of merged subarray

  // values remaining in first subarray and second subarray
  while(i < size1 && j < size2){
    if (leftArray[i] <= rightArray[j]){
      arr[k] = leftArray[i];
      i++;
    } else {
      arr[k] = rightArray[j];
      j++;
    }
    k++;
  }

  // values remaining in first subarray (compared all values in second subarray)
  while(i < size1) {
    arr[k] = leftArray[i];
    i++;
    k++;
  }

  // values remaining in second subarray (compared all values in first subarray)
  while(j < size2) {
    arr[k] = rightArray[j];
    j++;
    k++;
  }
}

void mergeSort(int arr[], int l, int r) {
  if (l < r){  // this is the if statement that fixed the seg fault
    int m = l + (r-l)/2;
    mergeSort(arr, l, m);
    mergeSort(arr, m+1, r);
    merge(arr, l, m, r);
  }
}

int main(){
  int arr[] = {12, 11, 13, 5, 6, 7};  
  int size = sizeof(arr) / sizeof(arr[0]); 
  printf("Unsorted Array: ");
  printArray(arr, size);
  mergeSort(arr, 0, size - 1); // l < r always 
  printf("Sorted Array: ");
  printArray(arr,size);
}

0 个答案:

没有答案