Search code examples
c++memoryerror-handlingsegmentation-faultbad-alloc

Getting Error : terminate called after throwing an instance of 'std::bad::alloc' what(): std::bad_alloc


Getting an error Getting Error : terminate called after throwing an instance of std::bad_alloc what(): std::bad_alloc

#include <iostream>
#include <inttypes.h>

using namespace std;

int64_t fibonacci(int64_t n,int64_t m) {
    int64_t *fibarray = new int64_t[n];
    for(int64_t i=0; i<n; i++)
    {
        if(i<=1)
            fibarray[i]=i;
        else
            fibarray[i]=(fibarray[i-1]+fibarray[i-2])%1000;
    }
    int64_t rett = (fibarray[n-1]%m);
    delete []fibarray;
    return rett;
}

int main() {
    int64_t n=0,m=0;
    cin>>n>>m;
    cout<<fibonacci(n+1,m);
}

Why std::bad_alloc has been thrown in this case?

i am calculating it for 2816213588


Solution

  • As others have already pointed out, it's likely a problem with n being too large.

    try replacing

    int64_t *fibarray = new int64_t[n];
    

    with

    int64_t *fibarray = new(nothrow) int64_t[n];
    if (fibarray == nullptr) return -1; // now check for null
    

    Check for null before even entering the loop. This is good practice especially since you expose the values of n and m to the user without any limits or checks for validity.