c++error-handlingdynamic-memory-allocationbad-allocalloc

I am getting bad_alloc error in c++ program


I wrote a c++ program but I am getting an error. I am not understanding the reason why I am getting the error. Please help me with how to fix this.

This is my code :

#include <bits/stdc++.h>
#define endl "\n"
#define int long long
using namespace std;

void solve() {
    int n, x;
    cin >> n >> x;
    cout << n << x;
    vector <int> in(n);
    for (auto &p : in)
        cin >> p;

    vector<int> vect;
    vect = in;

    int cnt = 0;
    int l = n;
    for (int i = 0; i < l; i++) {
        if (vect[i] % 2 == 0) {
            while (x--) {
                vect.push_back(vect[i] / 2);
                l++;
            }
        }
        else {
            cnt = i;
            break;
        }
    }
    int sum = 0;
    for (int i = 0; i < cnt; i++) {
        sum += vect[i];
    }
    cout << sum << endl;
}


signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >> t;
    while (t--) {
        solve();
    }
}

The input is :

2 1 2 12 4 2 4 6 8 2 

This is the error which I am getting on compiling it in sublime text :

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
[Finished in 4.0s]

Solution

  • The problem is in the treatment of the variable x. Don't ask me what the solution is but I can describe the problem.

            while (x--) {
                vect.push_back(vect[i] / 2);
                l++;
            }
    

    The first time this loop runs x equals two. So two items are added to the vector and x takes the value -1.

    The next time this loop runs x starts at -1 and so the loop runs until you run out of memory and get a bad_alloc exception.