Page 1 of 1

Strange behaviour under GCC 3.3

Posted: Mon Aug 09, 2004 2:35 pm
by Ilham Kurnia
Hi,

I wrote the following code, which basically tries to enlist all primes within a certain range.

[c]
#include <string.h>
#include <math.h>

int p[35000];
int li[5000];
int c;

void precalc()
{
int i, j;

memset(&p, 0, sizeof(p));
memset(&li, 0, sizeof(li));
c = 0;
p[1] = 1; p[2] = 0;
for (i = 2; i < 35000; i++)
{
if (!p)
{
for(j = i + i; j <= 35000; j += i) p[j] = 1;
li[c++] = i;
}
if (i < 10) printf("%d\n", li[0]);
}
}

int main()
{
int i, j, k, l, pr, t, fr, to;

precalc();

scanf("%d", &t);
for (i = 0; i < t; i++)
{
if (i) printf("\n");
scanf("%d %d", &fr, &to);
if (fr <= 1) fr++;
for (j = fr; j <= to; j++)
{
k = (int) (sqrt(j));
pr = 1;
for (l = 0; l < c && li[l] <= k; l++)
if (j % li[l] == 0) { pr = 0; break; }
if (pr) printf("%d\n", j);
}
}
return 0;
}
[/c]

When I tried to run it after compiling it using GCC 3.3, the value of li[0] changed from 2 to 1 after it finishes the precalc() function. It's rather bizzare because I don't see why the value of li[0] can change like that.

Can anyone help me? Thx in advance.

Posted: Mon Aug 09, 2004 4:07 pm
by little joey
p[95000] has the same address as li[0], so if you set p[95000] to 1, li[0] will be 1 too. Nothing to do with gcc, everything with writing outside the range of an array...

Posted: Mon Aug 09, 2004 4:56 pm
by Ilham Kurnia
little joey wrote:p[95000] has the same address as li[0], so if you set p[95000] to 1, li[0] will be 1 too. Nothing to do with gcc, everything with writing outside the range of an array...
Ah I see.. :oops:
Thx!