I am using sieve method to print all the prime numbers to a file. My code is as below:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE* file = fopen("primeList.txt","w ");
bool* x;
// long upLimit=100;
long upLimit=2000000000;
x=(bool*) calloc(1,upLimit);
long i=upLimit;
while(i--){
*(x i)=true;
}
*(x 1)=false;
*(x 2)=true;
*(x 3)=true;
int cnum=2;
int count=0;
while(cnum<upLimit){
if(*(x cnum)){
fprintf(file, "%d\n",cnum);
count ;
int compNum=cnum*2;
while(compNum<upLimit){
*(x compNum)=false;
compNum =cnum;
}
}
cnum =1;
}
fprintf(file, "Count is : %d\n", count);
fflush(file);
fclose(file);
return 0;
}
The last few lines from outfile is as below:
I am expecting count of primes to be the last line. Please help with the issue. Thanks in advance.
CodePudding user response:
Running the code with debug symbols, I can observe on my machine that it is reliably segfaulting at line 26: *(x compNum)=false;
Issuing p compNum
in gdb gives us the clue: compNum
has overflown to negative and now the code is trying to reference memory address that's not within process limits.
In other words, the output is not cut at the "Count" but earlier, in the middle of fprintf
in your system (and mine).
CodePudding user response:
Possible wrong size allocation.
Code assumes bool
is size 1.
bool* x;
long upLimit=2000000000;
//x=(bool*) calloc(1,upLimit);
// Should be
x = calloc(sizeof *x, upLimit);
// Add test
if (x) {
long i=upLimit;
while(i--){
*(x i)=true;
}