i cant understand why this happens

i m making a simple implentation of sieve of eratosthenes algorithm but code doesnt run on gcc

``````// calculate primes from 1 to 100
#include <stdio.h>
#include <math.h>

int main() {

unsigned long i,x[99],w;

for ( i=1; i<100; i++ ) {

x[i] = i+1;

}

for ( i=2; i<100; i++ ) {

if ( x[i] % 2 == 0 ) {

x[i] = 0;

}

}

for ( i=3; i<sqrt(100); i++ ) {

if ( x[w] != 0) {

for ( w=i; w<100; w++ ) {

if ( x[w] % i == 0 ) {

x[w] = 0;

}
}
}
}

for ( i=1; i<100; i++ ) {

if ( x[i] != 0 ) {

printf("prime number: %lu\n", x[i]);

}

}

getchar();

return 0;

}``````

any help?

3
Contributors
5
Replies
6
Views
9 Years
Discussion Span
Last Post by kostasxx

When running this code, variable w contains an unknown value, this will nearly always cause an array override (unless you've much much luck).
You've to (explicitly) assign w a value as well, before using it anywhere in your program.

``````for ( i=3; i<[B]sqrt(100)[/B]; i++ ) {

if ( [B]x[w][/B] != 0) { [B]// This will cause a segmentation fault[/B]

for ( w=i; w<100; w++ ) {

if ( x[w] % i == 0 ) {

x[w] = 0;

}
}
}
}``````

BTW, If I remember right, sqrt(100) equals 10, so why not just writing 10 instead?

Edit:: For anyone who thinks the code might not be compiling under gcc: I can confirm it compiles.

some compilers will initialize variables to zero. but there is no requirement in the C "rules" for them to do so.

therefore, most compilers will not initialize variables you declare, and so their contents are undefined until you do so. they will contain whatever bit pattern previously existed at whatever memory location is being used, and will likely result in some very large positive or negative number.

So never assume your declared variables are initialized. be certain that you have initialized them, or have otherwise set them to equal some known value, before using them.

.

oh

what a dumb mistake i made

sorry, thanks for help

oh

what a dumb mistake i made

sorry, thanks for help

if it's a dumb mistake, then we're all dumb. even experienced programmers will sometimes forget to initialize variables. it's probably one of the most common bugs.

:)