Hi everyone,
I'm trying to implement Eratosthenes Sieve and I am getting a seg fault on my first scanf function. I'm very new to C and am just using nano to write the code and gcc to compile it. Here is my code:
Never mind if my algo isn't quite right yet, the problem is the printf in main never executes and instead I get a seg fault Any idea or hints as to why that might be? I'm really stuck!Code:#include <stdio.h> #include <stdlib.h> void PrintPrimes(const int Max) { int i = 0, j = 0; int* PossiblePrimes = (int*) malloc((Max - 2) * sizeof(int)); printf("Test 2"); if(!PossiblePrimes) { printf("Error: Out of Memory"); return; } printf("Test 3"); for(i = 0; i < Max - 2; i++) { *(PossiblePrimes + i) = i + 2; } printf("Test 4"); i = 0; while(i < Max - 2) { if(PossiblePrimes[i] != 0) { for(j = 0; PossiblePrimes[i] * j < Max - 2; j++) { PossiblePrimes[(i * j) - 2] = 0; } } i++; } for(i = 0; i < Max - 2; i++) { if(PossiblePrimes[i] != 0) printf("%d\n", PossiblePrimes[i]); } free(PossiblePrimes); return; } int main() { int UserMax = 0; scanf("%d", &UserMax); printf("Do I get to here?"); if(UserMax >= 2) PrintPrimes(UserMax); return 0; }
EDIT: It only seg faults if I input a number greater than 10!?
Thanks for your time, much appreciated.
James