簡體   English   中英

是什么造成分段錯誤?

[英]What is causing a segmentation fault?

我一直在嘗試編寫一個確定數字是否為質數的程序。 我是基於Eratosthenes篩子制作的。 無論如何,我的程序適用於少量數字(15485863有效),但是如果使用大量數字(例如17485863),則會收到分段錯誤。 我使用的是無符號長整型,並且我認為我沒有超過其最大值。 我只是看不到我做錯了什么。 預先感謝您的協助!

#include <iostream>
#include <limits>

using namespace std;

bool soe (unsigned long long);

int main (void)
{
 unsigned long long x = 17485863;
 bool q = soe(x);

 cout << x << " is ";
 if(q)
  cout << "prime." << endl;
 else
  cout << "not prime." << endl;

 return 0;
    }

    bool soe(unsigned long long input)
    {
 unsigned long long arrayLength = input%2 + input/2;
 unsigned long long index = 2;
 unsigned long long greatestMult = 0;
 bool array[arrayLength];

 array[0] = true; //ignore true values in the array
 array[1] = true;
 do{
  array[index] = false;
 }while(++index < arrayLength);

 index = 2;

 do
 {
  if(input%index != 0)
  {
   greatestMult = input/index;
   while(index*greatestMult > arrayLength)
    greatestMult--;
   do
   {
    array[index*greatestMult] = true;
   }while(--greatestMult > 0);

   do
   {
    if(!array[index])
     break;
   }while(++index < arrayLength);

  }
  else
  {
   cout << endl << input << " is divisble by " << index << endl;
   return false;
  }
 }while(index < arrayLength);

 return true;
    }

請注意,long long和使用變量來標注自動數組都不是C ++的一部分-它們是gcc提供的擴展,如果可移植性成為問題,則不應使用。

要解決您的問題,請按以下方式確定數組的尺寸:

 bool array[arrayLength];

如果arrayLength值太大,將導致堆棧溢出(從而導致段錯誤)。 請改用std :: vector,但要注意內存不是無限資源。

在第24行上,您具有: bool array[arrayLength]; 您不能像這樣在堆棧上聲明數組。 程序在第29行崩潰。您需要使用new / delete在堆上聲明它;

某種程度的影響(我可能在那里漏了一兩個漏,但您明白了);

 //Beginning on Line 28
 bool *array = new bool[arrayLength];

 array[0] = true; //ignore true values in the array
 array[1] = true;
 do{
  array[index] = false;
 }while(++index < arrayLength);

 index = 2;

 do
 {
  if(input%index != 0)
  {
   greatestMult = input/index;
   while(index*greatestMult > arrayLength)
    greatestMult--;
   do
   {
    array[index*greatestMult] = true;
   }while(--greatestMult > 0);

   do
   {
    if(!array[index])
     break;
   }while(++index < arrayLength);

  }
  else
  {
   cout << endl << input << " is divisble by " << index << endl;
   delete [] array;
   return false;
  }
 }while(index < arrayLength);

 delete [] array;
 return true;
    }

產量

g++ -g test.cpp
gdb ./a.out
...clipped...
(gdb) run 
Starting program: /Users/nextraztus/a.out 
Reading symbols for shared libraries ++. done

17485863 is divisble by 3
17485863 is not prime.

Program exited normally.
(gdb) 

index * greatestMult可能等於arrayLength,因此您可以覆蓋數組末尾的最后一個元素。

同樣,在堆棧上分配大數組可能會導致問題,具體取決於操作系統。 一些系統將擴展堆棧很多,而其他系統將無法擴展。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM