I am coding the maximum subarray problem on C and am facing a segFault error.
I tested the find_max_crossing_subarray function alone and it worked fine. However, when I added the find_maximum_subarray function, the error occurred. Any idea what is wrong with my code?
Thx
#include <stdio.h>
#include <limits.h>
typedef struct Tuple{
int max_left;
int max_right;
int left_plus_right;
}Tuple;
struct Tuple find_max_crossing_subarray(int A[], int low, int mid, int high){
int left_sum = INT_MIN;
int sum = 0;
int i;
int max_left;
int max_right;
for (i = mid; i >= low; i--){
sum += A[i];
if (sum > left_sum){
left_sum = sum;
max_left = i;
}
}
int right_sum = INT_MIN;
sum = 0;
for (i = mid + 1; i <= high; i++){
sum += A[i];
if (sum > right_sum){
right_sum = sum;
max_right = i;
}
}
Tuple r = {max_left, max_right, left_sum+right_sum};
return r;
}
struct Tuple find_maximum_subarray(int A[], int low, int high){
int mid;
Tuple r;
int left_sum;
int right_sum;
int cross_sum;
if (low == high){
r.max_left = low;
r.max_right = high;
r.left_plus_right = A[low];
return r;
}
else{
mid = (low+mid)/2;
Tuple r_left = find_maximum_subarray(A, low, mid);
Tuple r_right = find_maximum_subarray(A, mid+1, high);
Tuple r_cross = find_max_crossing_subarray(A,low, mid, high);
if (left_sum >= cross_sum && left_sum >= right_sum){
return r_left;
}
else if (right_sum >= cross_sum && right_sum >= left_sum){
return r_right;
}
else{
return r_cross;
}
}
}
int main(){
int A[10] = {-1,2,4,5,-6,2,-1,4,-5,-1};
int low = 0;
int high = 9;
struct Tuple avg;
avg = find_maximum_subarray(A, low, high);
printf("max_left: %d\n",avg.max_left);
printf("max_right: %d\n",avg.max_right);
printf("left_plus_right: %d\n",avg.left_plus_right);
}
EDIT:
Output of gdb executable then run
Starting program: path_to_executable/maxSubArray
Program received signal SIGSEGV, Segmentation fault.
0x0804854d in find_maximum_subarray ()
typedefthestructasTupleand then keep referring to it asstruct Tuple-- you should probably pick one or the other to do.left_sum,right_sum, andcross_sumuninitialized, unless I'm misunderstanding your code. That wouldn't cause a segfault, though.