我有一個素數生成器,它生成unsigned int count
素數並將它們存儲在一個全局聲明的動態分配數組中numList globalPrimes
numList只是typedef unsigned int *numList
。如果計數的值是0,它被忽略,直到先前計算方法爲質數的值超過unsigned int until
其忽略,除非數爲0奇怪的realloc行爲奇/偶netbeans
numList getPrimes(unsigned int count, unsigned int until)
{
unsigned int i, j;
unsigned int p = 0;
char b=1;
if(globalPrimes==NULL)
{
b=0;
globalPrimes = calloc(count>0? count:until, sizeof(int));
if(globalPrimes==NULL)
return NULL;
}
globalPrimes[0]=2; //set first 2 prime #'s in list
globalPrimes[1]=3;
for(i=2, p=5; count!=0? (i<count):(globalPrimes[i-1]<=until); p+=2) //iterate until it finds every prime number. Increments p by 2 starting from the third prime
{
if(globalPrimes[i]!=0) //if the current prime was preordained (a value was set already) skip to the next prime
{
p=globalPrimes[i++];
continue;
}
else if(globalPrimes[i]==0) //if it is 0, allocate the extra memory and find next prime
{
if(b)
globalPrimes=(numList)realloc((void *)globalPrimes, sizeof(int)*((count==0)? (until):(count+1)));
b=0;
}
for(j=0; (p%globalPrimes[j]) && globalPrimes[j]*globalPrimes[j]<p; j++); //loop through all previous primes until past half of p
if(p%globalPrimes[j]) //if the prime is still not divisible by the previous prime
globalPrimes[i++]=p; // save as the next prime
}
globalPrimes[i]=0;
globalPrimes=(numList)realloc((void *)globalPrimes, (i+(i%2)+1)*sizeof(int));
return globalPrimes;
}
在一些測試中,它計算質數,我發現了一個奇怪的錯誤。在與realloc
netbean(gcc編譯器)的倒數第二行給我一個「信號」,我認爲它就像運行時異常。對話框顯示錯誤是SIGABRT,並且它在不處於調試模式時中止程序。我發現這個錯誤只發生在count爲奇數時。即使我修改realloc的參數以使它始終傳遞偶數,仍然存在錯誤。但是,當我修改計數只是在函數的開始,它工作正常。我無法弄清楚爲什麼這個奇怪的細節會導致這種奇怪的行爲。
[valgrind](http://valgrind.org/)是你的朋友。 –
調試器?解釋 – bathtub
你傳遞給'getPrimes'的參數是什麼? (我正在測試這個) – Xymostech