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

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

获取错误获取错误:抛出 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);
}

为什么在这种情况下会抛出 std::bad_alloc

我计算的是 2816213588

正如其他人已经指出的,这可能是 n 太大的问题。

尝试替换

int64_t *fibarray = new int64_t[n];

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

甚至在进入循环之前检查空值。这是一个很好的做法,尤其是因为您向用户公开了 nm 的值,没有任何限制或检查有效性。