You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++递归计算数组元素和触发Segmentation fault问题求助

Fixing the Segmentation Fault in Your Recursive Array Sum Function

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:26:51