Reputation: 6525
While trying to generate a vector of random numbers I stumble across a std::bad_alloc error. Here's my code:
#include "search.h"
#include "gtest/gtest.h"
int _size = 100;
std::vector<int> GetSortedVector(int size){
//init vector
std::vector<int> v(size);
//fill with random numbers
for (std::vector<int>::size_type i=0; i < v.size(); i++)
v.push_back( std::rand()%(2*size) );
//return the setup vector
return v;
}
//triggered automatically
TEST(BinarySearch, NonUniqueSorted){
std::vector<int> v = GetSortedVector(_size);//nothing moves farther than this line
}
P.S.: I do use generate()
by now, but am still curious why it failed.
Upvotes: 5
Views: 1892
Reputation: 258618
v.push_back
increases the size, so i<v.size()
is never false
.
Since your vector is already size
in length, you need to fill it with
for (std::vector<int>::size_type i=0; i < v.size(); i++)
v[i] = std::rand()%(2*size);
or use reserve
instead:
std::vector<int> v;
v.reserve(size);
keep the push_back
and check against size
. I won't suggest std::generate
because you said you're already doing it like that.
Upvotes: 8
Reputation:
Zoom into the following part:
for (std::vector<int>::size_type i=0; i < v.size(); i++)
v.push_back( std::rand()%(2*size) );
Every time you call push_back()
, vector's size is increased by 1. Therefore, i < v.size()
will never evaluate to false and your loop will go on until you run out of memory. One of the possible ways to fix it is to capture size()
once, for example:
for (std::vector<int>::size_type i=0, s = v.size(); i < s; i++)
v.push_back( std::rand()%(2*size) );
Upvotes: 2