gpt4 book ai didi

c++ - 获取错误:在抛出 'std::bad::alloc' what(): std::bad_alloc 的实例后调用终止

转载 作者:行者123 更新时间:2023-11-30 05:00:42 26 4
gpt4 key购买 nike

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

为什么在这种情况下会抛出 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

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

关于c++ - 获取错误:在抛出 'std::bad::alloc' what(): std::bad_alloc 的实例后调用终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50643892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com