Hii I am recieving the error of SIGMABRT
can anyone help with this ??
// { 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)
{
arr =new int[n];
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
{
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
CodePudding user response:
You do
arr =new int[n];
and to initialize the array you do
for( int i =0; i<=n;i )
That loop will go out of bounds of the array. Since array undexes are zero-based, an array of n
elements will have valid indexes from 0
to n - 1
. Your loop uses n
as an index.
Using out of bounds indexes leads to undefined behavior.
Change loop condition to less than rather than less than or equal:
for( int i = 0; i < n; i )
Also, the first thing you do in the recursion_fibo_series
function is:
if(arr[n]!=-1)
where you again use index n
as the index, which is out of bounds.
And you continue to do that inside this function.
CodePudding user response:
This is an out of bounds array access
arr = new int[n];
for (int i = 0; i <= n; i )
{
arr[i]=-1;
}
You want arr = new int[n 1];
.