递归实现斐波那契数列的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 from0ton-1. But your loop runsfor(int i=0; i<=n; i++), which tries to write toarr[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 toarr[0]andarr[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=0andn=1—this skips array creation entirely for small values and eliminates the out-of-bounds risk whenn=0. - Array Size Adjustment: Changed
new int[n]tonew int[n+1]so the array can safely hold indices from0ton, making your loopi<=nvalid. - Optional Overflow Fix: For large values of
n, Fibonacci numbers will quickly exceed the limit ofint. 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, thenrunto trigger the crash, andbtto 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
相关产品推荐
相关产品推荐

