c++ - Large vector "Segmentation fault" error -
i have gathered large amount of extremely useful information other peoples' questions , answers on so, , have searched duly answer 1 well. unfortunately have not found solution problem.
the following function generate list of primes:
void genprimes (std::vector<int>* primesptr, int upperbound = 10) { std::ofstream log; log.open("log.txt"); std::vector<int>& primesref = *primesptr; // populate primes non-neg reals (int = 2; <= upperbound; i++) primesref.push_back(i); log << "generated reals successfully." << std::endl; log << primesref.size() << std::endl; // eratosthenes sieve remove non-primes (int = 0; < primesref.size(); i++) { if (primesref[i] == 0) continue; int jumpstart = primesref[i]; (int jump = jumpstart; jump < primesref.size(); jump += jumpstart) { if (primesref[i+jump] == 0) continue; primesref[i+jump] = 0; } } log << "executed eratosthenes sieve successfully.\n"; (int = 0; < primesref.size(); i++) { if (primesref[i] == 0) { primesref.erase(primesref.begin() + i); i--; } } log << "cleaned list.\n"; log.close(); }
is called by:
const int size = 500; std::vector<int>* primes = new std::vector<int>[size]; genprimes(primes, size);
this code works well. however, when change value of size larger number (say, 500000), compiler returns "segmentation error." i'm not familiar enough vectors understand problem. appreciated.
you accessing primesref[i + jump]
i
primesref.size() - 1
, jump
primesref.size() - 1
, leading out of bounds access.
it happening 500 limit, happen not have bad side effects out of bound access @ moment.
also note using vector
here bad choice every erase have move of following entries in memory.
Comments
Post a Comment