I've been trying to implement the concept of merging two dynamic sequences, which are already sorted when provided as input. Why is it producing 'Segmentation Fault' every time? The program first takes the size of two sequences and dynamically allocates memory for them. After the elements are taken as input, a function named merge() is called to implement the concept. It takes two pointers to the sequence and returns another sequence of twice the size of the entered sequences having merged sequences. Here, one should note that input sequences are already sorted.
#include <stdio.h>
#include <stdlib.h>
int* merge(int*, int*, int);
int main() {
int *arr1, *arr2, *res;
int size, i;
printf("Enter the size of the array to be entered: ");
scanf("%d", &size);
arr1 = (int*)malloc(size * sizeof(int));
arr2 = (int*)malloc(size * sizeof(int));
if (arr1 == NULL || arr2 == NULL)
exit(1);
printf("Enter the elements for array 1 : \n");
for (i = 0; i < size; i++)
scanf("%d", arr1 + i);
printf("Enter the elements for array 2 : \n");
for (i = 0; i < size; i++)
scanf("%d", arr2 + i);
res = merge(arr1, arr2, size);
if (res != NULL){
for (i = 0; i < 2 * size; i++)
printf("%d ", *(res + i));
}
else
printf("The merging is not possible!");
free(arr1);
free(arr2);
return 0;
}
int* merge(int* obj1, int* obj2, int size) {
int* temp = (int *)malloc(2 * size * sizeof(int));
int i, j, count;
i = j = count = 0;
if (temp == NULL)
return NULL;
while (count < 2 * size){
while (*(obj1 + i) <= *(obj2 + j)){
*(temp + count) = *(obj1 + i);
count++;
i++;
}
while (*(obj2 + j) <= *(obj1 + i)){
*(temp + count) = *(obj2 + j);
count++;
j++;
}
}
return temp;
}