2012-07-06 94 views
2

我目前正在建設一個素數取景器,和我有記憶問題:C++內存問題

這可能是由於堆的腐敗,這表明在PrimeNumbers.exe或任何錯誤它已加載的DLL。

PS。如果這不是找到素數的方法,請不要對我說,我想弄清楚自己!

代碼:

// PrimeNumbers.cpp : main project file. 

#include "stdafx.h" 
#include <vector> 

using namespace System; 
using namespace std; 

int main(array<System::String ^> ^args) 
{ 
Console::WriteLine(L"Until what number do you want to stop?"); 
signed const int numtstop = Convert::ToInt16(Console::ReadLine()); 
bool * isvalid = new bool[numtstop]; 


    int allattempts = numtstop*numtstop; // Find all the possible combinations of numbers 

    for (int currentnumb = 0; currentnumb <= allattempts; currentnumb++) // For each number try to find a combination 
    { 
     for (int i = 0; i <= numtstop; i++) 
     { 
      for (int tnumb = 0; tnumb <= numtstop; tnumb++) 
      { 
       if (i*tnumb == currentnumb) 
       { 
        isvalid[currentnumb] = false; 
        Console::WriteLine("Error"); 
       } 
      } 
     } 
    } 

    Console::WriteLine(L"\nAll prime number in the range of:" + Convert::ToString(numtstop)); 

    for (int pnts = 0; pnts <= numtstop; pnts++) 
    { 
     if (isvalid[pnts] != false) 
     { 
      Console::WriteLine(pnts); 
     } 
    } 

return 0; 
} 

我沒有看到內存的問題。

請幫忙。

回答

5

您正在分配numtstop布爾值,但是您使用範圍從0到numtstop*numtstop的變量對該數組進行索引。這將嚴重超出numstop的值,大於1

您應該分配更多的布爾值(numtstop*numtstop)或使用不同的變量來索引到isvalid(例如,i,取值範圍爲0numstop)。我很抱歉,由於你的要求不要評論你的素數尋找算法,我不能更精確。


P.S.如果您想閱讀關於尋找小素數的內容,請參閱 great book by Dijkstra的鏈接。他教你如何爲35到49頁的前1000個素數構建一個程序。

0

問題是您在託管的C++/CLI代碼中使用本機C++。當然,使用新的無刪除。

0
`currentnumb` : 

大於數組的大小,這只是numtstop。你可能會走出界限,這可能是你的問題。

0

你從來沒有delete[]你的isvalid本地,這是一個內存泄漏。