简体   繁体   中英

I keep getting a std::bad_alloc error in C++

So I am making a program for Project Euler #14 and I have this

#include <iostream>
#include <vector>

using namespace std;

vector <int> CollatzSequence (int n)
{
    vector <int> numbers;
    int currentNumber = n;
    while (currentNumber != 1) {
        numbers.push_back(n);
        if (currentNumber%2 == 0) {
            currentNumber /= 2;
        } else {
            currentNumber *= 3;
            currentNumber += 1;
        }
    }
    numbers.push_back(1);
    return numbers;
}

int main()
{
    int largestNumber = 0;
    int currentNumber = 2;
    while (currentNumber < 1000000) {
        if (CollatzSequence(currentNumber).size() > largestNumber) {
            largestNumber = currentNumber;
        }
        currentNumber++;
    }
    cout << largestNumber;
    return 0;
}

But I keep getting this error

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

I am new to C++ but I don't know what this error means or how to fix it. Does anyone know how to fix this?

std::bad_alloc is thrown when allocation of memory fails, in your code this happens when allocating memory for std::vector returned. std::vector requires contiguous memory, in your code, the size to be allocated might be causing the problem.

as @WhozCraig said in the comments, the function has no need to return the vector itself since only the size is used rather, simply add a counter inside the function and return that.

#include <iostream>
#include <vector>

using namespace std;

int CollatzSequence(int n)
{
    int currentNumber = n;
    int counter = 0;
    while (currentNumber != 1) {
        ++counter;
        if (currentNumber%2 == 0) {
            currentNumber /= 2;
        } else {
            currentNumber *= 3;
            currentNumber += 1;
        }
    }
    ++counter;
    return counter;
}

int main()
{
    int largestNumber = 0;
    int currentNumber = 2;
    while (currentNumber < 1000000) {
        if (CollatzSequence(currentNumber) > largestNumber) {
            largestNumber = currentNumber;
        }
        currentNumber++;
    }
    cout << largestNumber;
    return 0;
}

maybe also consider moving from int to std::uint64_t like @Pablochaches suggested in the comments

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM