I wrote this code to find the xth greatest prime numbers:
for (int i = 3 /* 2 has already been added to the list */; i < maxNumber; i += 2) {
for (int tested = 0; ; tested++) {
if (primes[tested] == 0) {
break;
}
if (i % (int) primes[tested] == 0) {
goto loop;
}
}
count++;
if (count == primesSize) {
primesSize += 2000;
primes = (double*) realloc(primes, sizeof(double) * primesSize);
}
primes[count - 1] = i;
printf("Prime number #%d: %d\n", count, i);
printf("Prime size: %d\n", primesSize);
loop: /* statement that does nothing */ if (1) {}
}
However it returned a "Floating point exception" when using big numbers (> 8,000).
When happens here:
- The user chooses a number.
maxNumber
is set to the square root of the chosen number.- Firstly, a double pointer of size
1000 * sizeof(double)
is allocated. It is stored in theprimes
variable. - If a number is found to be prime, it is added to the array represented by the pointer.
- When the 1,000th number is added to the array, the
primes
pointer is reallocated to store 2,000 more numbers.
- When the 1,000th number is added to the array, the
When I used gdb
to find out the cause of the error, I found that this part was the cause of problem:
for (int tested = 0; ; tested++) {
if (primes[tested] == 0) {
break;
}
if (i % (int) primes[tested] == 0 /* breaks here */) {
goto loop;
}
}
Update: I thought the first if
statement would catch that issue, because printf("%f", primes[tested])
prints 0. However, it doesn't and the "break" is not executed.
When the code broke, tested
was 1001. I convert primes[tested]
to an integer because the modulo arithmetic operation I use requires ints to work. However, when I print primes[tested]
from code it shows 0. If I print the value from gdb, I get 6.1501785659964211e-319.
What am I missing? Should I modify my call to realloc
to avoid this exception?