0

I have a program that generates prime numbers. This code works fine when i want the first 100 and 200 primes, but puts out a Floating point exception whenever I use a value above 300 for total. The problem seems to be in the array, but I don't understand what is happening.

#include<stdio.h>

int main()
{
    int total = 500;
    int primes[total];
    primes[0] = 2;
    int max = 1;
    int current = 3;
    int index = 0;
    printf("%d\n",2);
    while(max != total)
    {
        for(index = 0; index <= max + 1; index++)
        {
            if(index == max + 1){
                primes[index] = current;
                printf("%d\n",current);
                max = max + 1;
                current = current + 1;
                break;
            } else {
                if(current % primes[index] == 0){
                    current = current + 1;
                    break;
                }
            }
        }
    }
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
user1445218
  • 105
  • 3
  • 7

2 Answers2

4

You have to ensure the expression current % primes[index] is never evaluated with a 0 value for primes[index]. A 0 value as the right operand of % operator invokes undefined behavior in C.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • When I run his code adjusting the array to be +1 bigger than total for the off by 1 error on the array, and total only being 500 this never happens, may he edited his code to account for that error – Steve Sep 04 '14 at 22:58
  • @Steve when `index == 1` the expression `current % primes[index]` is evaluated but `primes[1]` is not initialized so if the value happens to be a `0` he gets a division by `0`. On you system you may have had a different uninitialized value for `primes[1]`. A simple way to fix this issue is to have something like `primes[1] = 3;` at the top of the program. – ouah Sep 05 '14 at 07:36
0

enter image description here

your accessing beyond the end of primes[], in the debugger you write primes[index] where index == 500.. primes[500] doesn't exist

Steve
  • 502
  • 3
  • 12
  • I know you want to gloss over my answer, but think about this, your corrupting your memory, reading from potentially corrupted memory and doing calculations on it, which is causing your FP exception. try: `int total = 501;` `int primes[500];` and see – Steve Sep 04 '14 at 22:48