我正在处理一小段代码,它为一组产生两个数字之间的所有素数。我决定使用一个筛子(我知道这可能是一种更有效的方式来做我想要的比我的代码使用它的方式)并且由于某种原因我得到一个SIGSEGV(分段错误)。我已经看了很多,我不知道出了什么问题。我无法在本地计算机上重现错误。我在访问越界时通常会发生此错误,但我不知道这是否就是这种情况。温柔,我是C的新手,总是坚持更高层次的东西。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char argv){
int numberOfSets;
scanf("%d", &numberOfSets);
int i;
int lowerBound, upperBound;
for(i=0; i < numberOfSets; i++){
scanf("%d %d", &lowerBound, &upperBound);
//allocating memory and initializing to Zero
int (*sieve) = malloc(sizeof(int) * (upperBound+1));
memset(sieve, 0, (sizeof(int) * (upperBound+1)));
//iterating through sieve for even numbers and marking them as non prime
int counter = 2;
if(sieve[counter] == 0)
sieve[counter] = 1;
int multiplier = 2;
int multiple = counter * multiplier;
while(multiple <= upperBound){
sieve[multiple] = -1;
multiplier++;
multiple = multiplier * counter;
}
//iterating through sieve (incrementing by two) and filling in primes up to upper limit
counter = 3;
while( counter <= upperBound){
if(sieve[counter] == 0)
sieve[counter] = 1;
multiplier = 2;
multiple = counter * multiplier;
while(multiple < upperBound){
sieve[multiple] = -1;
multiplier++;
multiple = multiplier * counter;
}
counter = counter + 2;
}
int newCount = lowerBound;
//check and print which numbers in the range are prime
while (newCount <= upperBound){
if(sieve[newCount] == 1)
printf("%d\n", newCount);
newCount=newCount+1;
}
//free the allocated memort
free(sieve);
}
}
答案 0 :(得分:0)
问题是我没有检查Malloc的结果。我试图分配一个大的数组,分配失败。这留下了我分配给null的数组,因此我正在访问它的边界。