TO_GA
TO_GA

Reputation: 185

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

When I run the code below, I receive an error like this:

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.

I think it may be caused by the "resize()" line, but I don't know how to fix it. Here is my code:

#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;
}

Upvotes: 0

Views: 3853

Answers (1)

M.M
M.M

Reputation: 141628

std::string::max_size() is likely to be a large number such as SIZE_MAX, e.g. 4 GB on 32-bit system or the square of that on 64-bit systems. So your program runs out of memory.

Your program does not even need that allocation since you immediately overwrite the first 2 strings with a single-character string! Maybe you were thinking of reserve instead of resize, but even then, you could reserve a much smaller amount than max_size.

NB. register is deprecated and will be removed in C++17.

Upvotes: 1

Related Questions