I was writing a Sieve Of Eratosthenes program in C and I've been wanting to run the program with giant values e.g. 200000000 for benchmarking / why not purposes.
void SieveOfEratosthenes(long int n)
{
int* prime;
prime = (int*)malloc(sizeof(int) * n 1);
for (long int i = 0; i < n 1; i ) {
prime[i] = 1;
}
long int c = 0;
long int p = 2;
while (p * p <= n) {
if (prime[p] == 1) {
for (long int i = p * p; i < n 1; i = p) {
prime[i] = 0;
c ;
}
}
p = 1;
}
std::cout << c << std::endl;
}
I've tried declaring the array normally with int prime[n 1] or int bool prime[100...] and I remember trying something with vectors at some point.
A lot of the errors I get are Read/Write Access Violations.
I'm not looking for a solution specific to my code, I just want to know a method I can use to initialize large arrays.
CodePudding user response:
Compile in x64 instead of x86. Malloc is limited to 32 bit integer limit in 32 bit build.
CodePudding user response:
malloc(sizeof(int) * n 1);
Let's use small numbers, let's say that n is 10. Let's say your sizeof(int) is 4 (a very reasonable assumption, but 8 will also work, if you adjust all the following math too). So. this will allocate 4*10 1, or 41 bytes.
for (long int i = 0; i < n 1; i ) {
prime[i] = 1;
}
This will then populate prime[0] through prime[10], if you work out the logic step by step. This adds up to 11 integer values, and since sizeof(int) is 4, this will scribble over 44 bytes of memory.
Unfortunately only 41 bytes were allocated, hence the resulting memory corruption and access errors.
CodePudding user response:
I see no essential problem with your code other than the minor issue with the order of operations:
prime = (int*)malloc(sizeof(int) * (n 1));
I slightly changed the logic to get the number of primes and it works fine online with 10^9: https://onlinegdb.com/M9fZJCZVb
