求助,找素数的程序,个数超过1000个后在win7 和 Xp 中出错,在Linux 超过9000以上报错
出错就是在win7中弹出对话框,“停止响应” ,在XP中立即退出,在linux中报 segment fault .程序代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> int main(void) { unsigned long *p_primes=0; unsigned int total; bool found=false; printf("input the number of primes ,at least 4\n"); fflush(stdout); scanf("%d",&total); fflush(stdin); total=total<=4?4:total; p_primes=(unsigned long *)malloc(total); if(p_primes==NULL){ printf("can't allocate memory !\n"); return 1; } *p_primes=2UL; *(p_primes+1)=3UL; *(p_primes+2)=5UL; unsigned int count=3U; unsigned long trial=5UL ; while(count<total){ trial+=2UL; for(size_t i=0;i<count;i++){ if(!(found=trial%*(p_primes+i))){ break; } } if(found){ *(p_primes+count++)=trial; } } for(size_t i=0;i<total;i++){ if(i%5==0){ printf("\n"); } printf("%lu\t",*(p_primes+i)); } printf("任意键退出"); fflush(stdout); getchar(); }