So, what the HELL is going on here... Here's the deal, I made this to find the highest prime factor of the number n (Yeah, w/e that number is, 600 billion something). The thing is, it will run, then all of a sudden it will stop working. Like I will run it say 10 times or so, then it will continuously keep crashing. Sometimes it will print 1 number, sometimes none, sometimes it will cause a runtime error, sometimes just NOTHING happens, I have no freaking idea what the hell is happening here... Also, if I change the array to type int, then run it, it will cause a crash, but then if I change it back to char it will start working again. Every time these crashes happen if I change it to int, run it, then to char it will magically start working again... My only guess is something weird is happening in memory. But I can't see what's wrong with this. Here's the code!

You have undefined behavior on the red line.
It tries to assign to s[10000] among others.

09-26-2008

matsp

Code:

for (x = 0; x < N; x++)
s[x] = 1;

while (y < x) {

when the for-loop ends, x will be the same value as N. So why not use N?

This overflows:

Code:

while ( i < N ) {
i+=y;
s[i] = 0;
}

if i + y > N you will go outsid the loop here, as you add y to i after checking if i is below N.

As to why it only causes crashes SOMETIMES, that's just the way "undefined behviour" works - it's like running a red light: Sometimes there's a car going across the junction the other direction with a green light that hits you, at other times it's clear and you get across unhurt.