Search code examples
c++c++11out-of-memorybad-alloc

Why does the following code throw std::bad_alloc?


I have written code to test how many of the same numbers are present in both arrays, but for some reason it throws 'std::bad_alloc' could anyone explain why? It only throws it when N = 1000000 for some reason, is it because I have allocated 4000000 bytes of memory?

Here's the code:

#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
#include <math.h>
#include <iomanip>

using namespace std;

int find_last_before_zero(const vector<int>& vec) {
 for (int i = vec.size() - 1; i >= 0; --i) {
    if (vec[i] != 0) return i + 1;
 }
return vec.size();
}

void gen_random_array(vector<int>& vec){
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dist(100000, 100200);

for(int i = 0; i < vec.size(); ++i){
    vec[i] = dist(gen);
}
}

void binSearchClient(int T){
int counters[4] = {0,0,0,0};
string names[4] = {"for n = 1000 = ", "for n = 10000 = ", "for n = 100000 = ", "for n = 1000000 = "};
for(int i = 0; i < T; ++i){
    int N = 1000;
    for(int k = 0; k < 4; ++k){
        N *= pow(10.0, k);
        vector<int> first(N), second(N);
        gen_random_array(first, N); gen_random_array(second, N);
        vector<int> intersection(N);
        sort(first.begin(), first.end()); sort(second.begin(), second.end());
        set_intersection(first.begin(), first.end(), second.begin(), second.end(), intersection.begin());
        counters[k] += find_last_before_zero(intersection);
            }
        }
    }
}
for(int i = 0; i < 4; ++i){
    cout << names[i] << setprecision(10) << std::fixed << (1.0 * counters[i]) / T << endl;
}
}

int main(){
binSearchClient(1);
}

Solution

  • In you first iteration you have N as 1000. Then in for(int k = 0; k < 4; ++k) you do N *= pow(10.0, k);. So for the first iteration N = 1000 (N(1000) * 10^0) The k becomes 1 and you N = 10000 (N(1000) * 10^1). Then k becomes 2 and N = 1,000,000 (N(10000) * 10^2). At k = 3 you get N = 1,000,000,000,000,000 (N(1,000,000) * 10^3) which is more than likely memory than you can allocate.