algorithm - Cant find out why this part of my code crash in C -


i'm sure it's simple, cant seem find why code crashes. beginning of program , crashes. finding prime numbers using sieve of eratosthenes (or partly).

#include<stdio.h> #include<stdlib.h>  int main(){     int i, j, k;      int *array = malloc(sizeof(int)*1500000);     int *temp = malloc(sizeof(int)*10000);  /***** step 1 : find prime numbers *****/      // initialize array 0     for(i=0; i<1500000; i++)         array[i] = 0;      // sieve algorithm     for(i=2; i<1500000; i++)         if(array[i] == 0){             j = i;             k = 0;             while(k<1500000){                 k = i*j;                 array[k] = 1;                 j = j + 1;             }         }     free(array);     free(temp);     return 0; } 

replacing:

            k = 0;             while(k<1500000){                 k = i*j;                 array[k] = 1;                 j = j + 1;             } 

with:

            while(i*j<1500000){                 array[i*j] = 1;                 j = j + 1;             } 

doesn't fix problems. why?

the problem here:

        k = 0;         while (k<1500000){             k = i*j;             array[k] = 1; /* error line */             j = j + 1;         } 

here index array, k, can > sizeof array , out of bounds error.

in code 1499999 , k 1499999. 1499999 * 1499999 = 2249997000001. in fact result might overflow not want.

always idea step through code examining logic. programming maths - check logic.

you use debugger step through code. although in case take looonnng time! or @ least run in debug mode , stop when exception , can examine variables @ point.


Comments