Home > Back-end >  Why segmentation fault in this simple C program?
Why segmentation fault in this simple C program?

Time:01-12

I am trying to merge two sorted subarrays. I have spent hourse of frustration removing segmentation fault error in vs code but with no success.

  • I am using a temporary array to store the newly ordered array.
  • comparing elements of two subarrays simultaneously and incrementing the index of the subarray whose arr[index] is smaller.
  • Copying the leftover elements of the subarray whose traversal index has not reached the end.
#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] << " ";
    }




}

CodePudding user response:

This is an infinite loop:

while(i <= end1 ){
    temp_arr[start1  ] = arr[i];
}

So is this one.

while(j <= end2){
    temp_arr[start1  ] = arr[j];
}

In both cases, since neither i, j, end1, nor end2 ever change in these loops, start1 will keep increasing way past the array boundary, introducing more undefined behavior on each iteration that makes an assignment.

That may not be your only bug.

  •  Tags:  
  • Related