I want to dynamically declare a boolean array for my C++ program and set its value to false.I am having issues with memory allocation I guess how and getting a dangling pointer I am trying to find prime numbers by Sieve of Eratosthenes I am trying to use boolean array dynamically but facing issues.
I am not trying to implement it using memset .
int limit = 2000000 ;
int crossLimit = sqrt(limit) ;
void SievePrime(int limit)
{
bool* boolArray = new bool[false] ;
for(int i =4;i<=limit ;i = i + 2)
{
boolArray[i] = true ; //getting error hereThread 1:
//EXC_BAD_ACCESS (code=2, address=0x100786000)
}
for(int j= 3 ;j<=crossLimit ; j= j+2){
if (not boolArray[j])
{
for(int k =j*j;k<=limit;k*=2)
{
boolArray[k] = true ;
}
}
}
double sum = 0 ;
for(int i =2 ; i<=limit ;i++)
{
if(!boolArray[i])
{
sum = sum + i ;
}
}
cout<<sum<<endl ;
}
expected output: 142913828922
error:Thread 1: EXC_BAD_ACCESS (code=2, address=0x100786000)
bool* boolArray = new bool[false] ;What do you think you're doing here ?new bool[...]should be the size of your array, it doesn't correspond to the value of your array elements. So the problem is that you are iterating through an array that isn't well allocatedfalseis0