gpt4 book ai didi

memory - C++内存问题

转载 作者:行者123 更新时间:2023-12-02 05:38:18 30 4
gpt4 key购买 nike

我目前正在构建素数查找器,但遇到了内存问题:

This may be due to a corruption of the heap, which indicates a bug in PrimeNumbers.exe or any of the DLLs it has loaded.

附言。如果这不是找到素数的方法,请不要告诉我,我想自己弄明白!

代码:

// 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;
}

我没有看到内存问题。

请帮忙。

最佳答案

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

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


附言如果您想阅读有关寻找小素数主题的内容,这里有一个链接 great book by Dijkstra .他在第 35..49 页教您如何构建前 1000 个素数的程序。

关于memory - C++内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11360224/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com