如何避免bad_alloc
下面代码中的错误。它说C调用abort
函数:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
SIGABRT
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main()
{
int n,p,count=0;
double l,t;
while(1)
{
cin>>n;
if(n==0)
break;
else
{
int * arr;
arr= new int[n+1];
for (int i=1; i<=n; i++)
arr[i]=0;
for(int i=2;i<=n;i++){
if(arr[i]==0)
{ p=i;
count++;
for (int j=2;p*j<=n;j++)
{
arr[p*j]=1;
}
}
}
delete[] arr;
l=(double(n))/(log(n));
t=(((count-l))/count)*100;
if(t<0)
t=(-1)*t;
printf("%.1lf\n",t);
}
count=0;
}
getch();
return 0;
}