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

递归实现斐波那契数列的C++代码触发SIGABRT错误,寻求解决帮助

Fixing SIGABRT Error in Your Memoized Fibonacci C++ Code

Let's walk through the issues in your code that are triggering the SIGABRT error, then fix them up properly.

1. The Root Cause: Array Out-of-Bounds Access

Your main problem comes from invalid memory access:

  • When you create the array with arr = new int[n];, the array only has space for indices from 0 to n-1. But your loop runs for(int i=0; i<=n; i++), which tries to write to arr[n]—a position that doesn't exist in the array. This out-of-bounds write corrupts memory and leads to the SIGABRT crash.
  • On top of that, if n=0, new int[0] creates an empty array, and then you try to assign values to arr[0] and arr[1]—both of which are way outside the array's bounds.

2. Step-by-Step Fixes

Here's the revised code with explanations for each change:

// { Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;

//User function Template for C++
class Solution {
    int *arr ;
public:
    int firstElement(int n) {
        // Handle edge cases first to avoid unnecessary array ops
        if(n == 0) return 0;
        if(n == 1) return 1;
        
        // Create array of size n+1 to fit indices 0 through n
        arr = new int[n+1];
        // Initialize all memoization entries to -1
        for( int i =0; i<=n;i++) {
            arr[i] = -1;
        }
        arr[0] = 0;
        arr[1] = 1;
        int k = recursion_fibo_series(n, arr);
        delete []arr;
        return k;
    }
    
    int recursion_fibo_series(int n, int arr[]) {
        if(arr[n] != -1){
            return arr[n];
        } else {
            // Optional: Add modulo to prevent integer overflow for large n
            arr[n] = recursion_fibo_series(n-1, arr) + recursion_fibo_series(n-2, arr);
            return arr[n];
        }
    }
};

// { Driver Code Starts.
int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n ;
        Solution ob;
        cout << ob.firstElement(n) << endl;
    }
    return 0;
}
// } Driver Code Ends

Key Changes:

  • Edge Case Handling: Added direct returns for n=0 and n=1—this skips array creation entirely for small values and eliminates the out-of-bounds risk when n=0.
  • Array Size Adjustment: Changed new int[n] to new int[n+1] so the array can safely hold indices from 0 to n, making your loop i<=n valid.
  • Optional Overflow Fix: For large values of n, Fibonacci numbers will quickly exceed the limit of int. If this is for a programming problem, you'll likely want to add a modulo operation (e.g., % 1000000007) to keep values within bounds.

3. Debugging Tips for Future Issues

  • When you hit SIGABRT in C++, it's almost always a memory issue (out-of-bounds access, double free, null pointer dereference). Use GDB to debug: run gdb ./your_executable, then run to trigger the crash, and bt to get a call stack showing exactly where the error happened.
  • Use Valgrind to check for memory leaks and invalid memory accesses—it's a powerful tool for catching these kinds of issues before they cause crashes.

内容的提问来源于stack exchange,提问作者Prashant Rai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 20:12:35