JoyGreen - 1 year ago 75

C++ Question

The following program seems to be causing a segmentation fault on the loop variable.

Could anyone help me understand what is going on please!

`std::vector<int> Euler::Utils::sieve(int n) {`

std::vector<bool> A(n, true);

using size_t = std::vector<bool>::size_type ;

size_t size = static_cast<size_t>(std::sqrt(n));

std::vector<int> result;

for (size_t i = 2; i < size; i++) {

if (A[i]) {

size_t i2 = static_cast<size_t>(std::pow(i, 2));

for (int j = 0; j < n; j++ ) {

A[i2 + j* i] = false;

}

}

}

for (size_t i = 2; i < A.size(); i++) {

if (A[i]) {

//Seg fault here.

std::cout << i << std::endl;

result.push_back(i);

}

}

return result;

}

Edit: The error is around the end at the result.push_back(i);

Answer Source

From a quick glance, I see that the vector A is of size n. But in the first nested for loop, array A is indexed on {i2 + j*i}. This expression can evaluate to a number greater than n as j runs from 0 to n-1. So, {i2 + j * i} can exceed the capacity of your vector which may be causing the seg fault. Full code will help us in verifying this.