簡體   English   中英

為什么在運行此代碼時收到std :: bad_alloc異常?

[英]Why do I receive a std::bad_alloc exception when running this code?

當我運行下面的代碼時,我收到這樣的錯誤:

拋出'std :: bad_alloc'實例后調用終止
what():std :: bad_alloc

該應用程序已請求運行時以一種異常方式終止它。 請與應用程序的支持團隊聯系以獲取更多信息。

我認為這可能是由“ resize()”行引起的,但我不知道如何解決。 這是我的代碼:

#include <cstdio>
#include <string>
#include <iostream>
using namespace std;

long long n, l, r;
string x[3];

int main()
{
    ios::sync_with_stdio(false);
    for (int i = 0; i <= 2; i++)
        x[i].resize(x[i].max_size());
    x[0] = '0';
    x[1] = '1';
    cin >> n >> l >> r;
    for (register long long i = 2; i <= n ; i++)
        x[i % 3] = x[(i - 2) % 3] + x[(i - 1) % 3];
    cout << x[n % 3].substr(l, r - l + 1) << endl;
    return 0;
}

std::string::max_size()可能是很大的數字,例如SIZE_MAX ,例如在32位系統上為4 GB或在64位系統上為平方。 因此您的程序內存不足。

您的程序甚至不需要分配,因為您立即用單個字符的字符串覆蓋了前2個字符串! 也許您在考慮reserve而不是resize ,但是即使那樣,您也可以保留比max_size小得多的金額。

NB。 不贊成使用register ,並將在C ++ 17中將其刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM