出现错误:抛出'std :: bad :: alloc'what():what std :: bad_alloc实例后终止终止

亚什·in那

遇到错误出现错误:抛出的实例后终止调用 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

Quadir Ali |

正如其他人已经指出的那样,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的值暴露给用户而没有任何限制或有效性检查。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

得到错误“抛出'std :: bad_alloc'what():whatstd :: bad_alloc实例后终止调用”

当我运行我的代码时,我不断收到此错误“在抛出 'std::bad_alloc' what(): std::bad_alloc 实例后调用终止”

C++ 抛出错误“在抛出‘std::bad_alloc’的实例后终止调用”

C ++错误:抛出'std :: bad_alloc'实例后终止调用

为什么在抛出'std :: bad_alloc'实例后终止调用?

Tensorflow MNIST:抛出'std :: bad_alloc'实例后调用终止

抛出'std::bad_alloc'的实例后调用C++终止

当我的训练数据很大时,为什么我会在抛出“ std :: bad_alloc实例”后收到“终止调用”?

TfLearn Confusion Matrix训练在std :: bad_alloc终止

C ++向量std :: bad_alloc错误

错误更改/ usr /权限后的'std :: bad_alloc'

Qt5抛出std :: bad_alloc

Std::bad_alloc 在 While 循环中间抛出

程序中的 C++ 向量 std::bad_alloc 错误

如何修复“std::bad_alloc”

what():std :: bad_alloc-我内存不足了吗?

在std :: filesystem :: path追加上的c ++ std :: bad_alloc

为什么返回vector <string>会抛出std :: bad_alloc异常?

附加 std 字符串时出现 bad_alloc 异常

std :: vector构造函数中的bad_alloc

'new'导致std :: bad_alloc在相对不大的分配上

C++ - memcpy 给出异常:std::bad_alloc

将Botan用于PKCS#11的std :: bad_alloc

级联两个向量时的std :: bad_alloc

创建 QQuickWidget 时的 std::bad_alloc 异常

大数据集的dijkstra计算期间的std :: bad_alloc

如果我得到std :: bad_alloc怎么办?

CPP - 未处理的异常 std::bad_alloc

Heroku上的节点应用程序段错误:std :: bad_alloc并退出代码134