为什么这个简单的 C++ 程序会出现分段错误?

Ary*_*an 0 c++ arrays sorting merge segmentation-fault

我正在尝试合并两个已排序的子数组。我花了几个小时的时间来消除VS Code 中的分段错误错误,但没有成功。

  • 我正在使用临时数组来存储新排序的数组。
  • 同时比较两个子数组的元素,并递增arr[index]较小的子数组的索引。
  • 复制遍历索引未到达末尾的子数组的剩余元素。
#include<iostream>
#include<math.h>
using namespace std;

void merge(int start1,int end1,int start2,int end2,int arr[],int temp_arr[]){
    int i = start1;
    int j = start2;
    while (i <= end1 && j <= end2)
    {
        if(arr[i] < arr[j]){
            //using start1 as index on purpose
            temp_arr[start1++] = arr[i];
            i++; 
        }else{
            temp_arr[start1++] = arr[j];
            j++;
        }
    }

    //if first array elements are left
    while(i <= end1 ){
        temp_arr[start1++] = arr[i];
    }

    //if second array elements are left
    while(j <= end2){
        temp_arr[start1++] = arr[j];
    }
    
}

int main(){
    int arr[] = {5,6,7,1,2,3};
    int n = sizeof(arr)/sizeof(int);
    int temp[n];//temporary array
    int a;
    //to find where the next sorted subarray begins
    for(int i = 0;i <n-1;i++){
        if(arr[i] > arr[i+1]){
            a= i;
            break;
        }
    }
    
    merge(0,a,a+1,n-1,arr,temp);

    for(int i = 0;i < n;i++){
        cout << temp[i] << " ";
    }




}
Run Code Online (Sandbox Code Playgroud)

sel*_*bie 6

这是一个无限循环:

while(i <= end1 ){
    temp_arr[start1++] = arr[i];
}
Run Code Online (Sandbox Code Playgroud)

这个也是如此。

while(j <= end2){
    temp_arr[start1++] = arr[j];
}
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,由于这些循环中的ijend1、 都不会end2改变,start1因此将继续增加超出数组边界,从而在每次进行赋值的迭代中引入更多未定义的行为。

这可能不是你唯一的错误。