C++内存问题

Mig*_*l P 2 memory numbers c++-cli

我正在构建一个素数查找器,并且遇到内存问题:

这可能是由于堆的损坏,这表明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;
}
Run Code Online (Sandbox Code Playgroud)

我没有看到内存问题.

请帮忙.

das*_*ght 5

您正在分配numtstop布尔值,但您使用范围从零到的变量索引该数组numtstop*numtstop.对于numstop大于的所有值,这将严重超出范围1.

您应该分配更多的布尔值(numtstop*numtstop)或使用不同的变量来索引isvalid(例如,i范围从0numstop).对不起,我不能比那更精确,因为你要求不评论你找到素数的算法.


PS如果你想阅读关于寻找小素数的话题,可以看到Dijkstra的本好书的链接.他教你如何为第35..49页的前1000个素数构建一个程序.