c++ - Segmentation fault (core dumped) only bigger input -
My code works perfectly if seive (n) is 1000000. If seive (n) is greater than 10000000, then it shows me the division fault (core dump). I have read about the mistake of division, but I could not solve it with it.
#include & lt; Stdio.h & gt; # Include & lt; Math.h> using namespace std; Init Sieve (long int n) {long int a [n]; (Long int i = 2; i & lt; = n; i + = 1) {a [i] = i; } Long end root = (int) sqrt (n); (Et c = 2; j & lt; = root; j ++) {for (int q = 2 * j; k & lt; n; k = k + j) {a [k] = 0; }} Int count = 0; {If (A [L]! = 0) count ++ for (intL = 2; L & lt; n; ++ l) } Printf ("% d \ n", count); } Int main () {seive (1000000); }
long int A [n];
This is an array on the stack. It's really big, if your stack is big enough to catch it in those cases it's not big enough and you'll receive a stack overflow error.
The solution includes:
Dynamically allocated memory: Long int * A = (long int *) Malloc (n * sizeof (long int));
Dynamically assigned memory C ++ style: long int * A = new long int [n];
Staticly allocated buffer (which is not on the stack): Stable long int a [n];
Make it global: take that line to 3 lines.
Comments
Post a Comment