为什么在 运行 这段代码时我会收到 std::bad_alloc 异常?

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

当我运行下面的代码时,我收到这样的错误:

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

我想这可能是"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 位系统上为 4 GB。所以你的程序内存不足。

您的程序甚至不需要分配,因为您会立即用 single-character 字符串覆盖前 2 个字符串!也许您考虑的是 reserve 而不是 resize,但即便如此,您也可以保留比 max_size 少得多的金额。

注意。 register 已弃用,将在 C++17 中删除。