2

I'm currently building a prime number finder, and am having a memory problem:

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.

PS. Please don't say to me if this isn't the way to find prime numbers, I want to figure it out myself!

Code:

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

I don't see the memory problem.

Please help.

4

4 回答 4

5

You are allocating numtstop booleans, but you index that array using a variable that ranges from zero to numtstop*numtstop. This will be severely out of bounds for all numstop values greater than 1.

You should either allocate more booleans (numtstop*numtstop) or use a different variable to index into isvalid (for example, i, which ranges from 0 to numstop). I am sorry, I cannot be more precise than that because of your request not to comment on your algorithm of finding primes.


P.S. If you would like to read something on the topic of finding small primes, here is a link to a great book by Dijkstra. He teaches you how to construct a program for the first 1000 primes on pages 35..49.

于 2012-07-06T10:15:34.590 回答
0

Problem is that you use native C++ in managed C++/CLI code. And use new without delete of course.

于 2012-07-06T10:13:36.383 回答
0
`currentnumb` :   

is bigger than the size of the array, which is just numtstop. You are probably going out of bound, this might be your issue.

于 2012-07-06T10:15:14.147 回答
0

You never delete[] your isvalid local, this is a memory leak.

于 2012-07-06T10:17:26.447 回答