C++递归计算数组元素和触发Segmentation fault问题求助
Hey there! Let's break down why your code is hitting a segmentation fault and how to fix it.
The Root Cause
The problem lies in how you're splitting the array for the right recursive call. Let's look at this line:
int y = findSum(arr, mid, e);
When your current interval [b, e] has b != e but they're adjacent (like b=0, e=1), mid will be (0+1)/2 = 0. This means the right call becomes findSum(arr, 0, 1)—exactly the same as the original call. You've created an infinite recursion loop! Each recursive call adds a new frame to the stack, and eventually, you run out of stack space, triggering a segmentation fault.
The Fix
To fix this, you need to split the array into non-overlapping, shrinking intervals. Change the right recursive call to start at mid + 1 instead of mid:
int y = findSum(arr, mid + 1, e);
This way, each recursive call works on a smaller subarray. When b == e, you hit the base case and return the single element, stopping the recursion.
Corrected Full Code
Here's the fixed version of your code:
#include <iostream> using namespace std; int findSum(int arr[], int b, int e) { if (b == e) return arr[b]; else { int mid = (b + e) / 2; int x = findSum(arr, b, mid); int y = findSum(arr, mid + 1, e); return x + y; } } int main() { int arr[] = {1, 6, 3, 10, 11, 4, 5, 9, 15, 2}; cout << findSum(arr, 0, 9) << endl; return 0; }
A couple of small notes beyond the fix:
- I replaced
<bits/stdc++.h>with<iostream>since that's all you need here—it's better practice to include only necessary headers. - Removed
system("pause")as it's Windows-specific and not needed for the program to function correctly.
Testing It Out
When you run this corrected code, it should output 66 (the sum of all elements in your array) without any segmentation faults.
内容的提问来源于stack exchange,提问作者Mayar Karout

