I was writing a simple commandline C++ program in native code to create a list of prime numbers up to a specified number, but I am running into Heap Corruption errors when I try to deallocate memory I no longer need before my sieve() function terminates.
The following is my program's code, and the problem is towards the end of the function when I try to release memory that I dynamically allocated to a bool array.
#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
int * sieve(int limit);
int main()
{
int x;
cout << "Please Enter a Number: " << endl;
cin >> x;
if (x = 0)
{
return 0;
}
sieve(x);
//Output code goes here
return main();
}
int * sieve(int limit)
{
//Create bool array, each element is a number, element 0 is 0.
//Idea for future use; use individual bits instead of
bool * a = new (nothrow) bool [limit];
//Set all to true
for (int x = limit; x >= 0; x--)
{
a[x] = true;
}
//Set Mutiples of Primes to False
for (int x = 2, max = (int) sqrt((double)limit); x <= max; x++)
{
for (int y = x << 1; y < limit; y += x)
{
a[y] = false;
}
}
//Count Primes
int i = 0;
for (int x = 2; x < limit; x++)
{
if (a[x])
{
i++;
}
}
//Create int array to store primes
int * b = new (nothrow) int [i];
//Fill array with primes
for (int x = 2, p = 0; x < limit; x++)
{
if (a[x])
{
b[p] = x;
p++;
}
}
//Release Memory used to store bool array
//The following two lines do not work
delete [] a;
delete a;
//Return Array of Primes to function call
return b;
}
When I compile my application with Visual Studio 2005 Standard Edition, the compilation occurs without an issue but when I try executing it, I receive the following error:
Debug Error!
Program: ...
HEAP CORRUPTION DETECTED: after Normal block (#134) at 0x00355DC0. CRT detected that the application wrote to memory after the end of the heap buffer.
Does anyone know how I can release memory without getting this error?
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.