This is some code I wrote for implementing Sieve of Eratosthenes:
#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>
#include <cstdlib>
int allPrimes (unsigned long n) {
std::vector<int> track (n, 0);
int index = 2;
int m = sqrt(n);
while(index < n) {
if (track[index] == 0) {
std::cout << index << std::endl;
int mul = 1;
while ((index <= m) && (n >= (index * ++mul))) {
track[index * mul] = 1;
}
}
index++;
}
}
int main() {
int num;
std::cin >> num;
allPrimes(num);
}
Strangely, whenever num is in the series 6, 10, 14, 18, 22, … the code aborts with the folloiwng stack while deallocating memory (runs okay for other n):
raise () from /lib64/libc.so.6
abort () from /lib64/libc.so.6
__libc_message () from /lib64/libc.so.6
malloc_printerr () from /lib64/libc.so.6
_int_free () from /lib64/libc.so.6
__gnu_cxx::new_allocator<int>::deallocate
std::_Vector_base<int, std::allocator<int> >::_M_deallocate
std::_Vector_base<int, std::allocator<int> >::~_Vector_base
std::vector<int, std::allocator<int> >::~vector
allPrimes (n=6) at allprimes.cpp:20
main () at allprimes.cpp:26
But I do not see the bug, or the logic behind these numbers spaced by 4. What is the bug here?
Here:
you allow
indexto run up ton, which is out of bounds. You needn-1, orwhile (index < n). There are other such indexing errors in the code, all of which lead to undefined behaviour.