How to avoid bad_alloc?
<p>How can I avoid the <code>bad_alloc</code> error in the code below. It says C
called <code>abort</code> function:</p>

<pre><code>terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
SIGABRT

#include&lt;iostream&gt;
#include&lt;math.h&gt;
#include&lt;conio.h&gt;
using namespace std;
int main()
{
  int n,p,count=0;
  double l,t;
  while(1)
  {
    cin&gt;&gt;n;
    if(n==0)
      break;
    else
    {
      int * arr;
      arr= new  int[n+1];
      for (int i=1; i&lt;=n; i++)
        arr[i]=0;
      for(int i=2;i&lt;=n;i++){
        if(arr[i]==0)
        {   p=i;
          count++;
          for (int j=2;p*j&lt;=n;j++)
          {   
            arr[p*j]=1;
          }
        }

      }
      delete[] arr;
      l=(double(n))/(log(n));
      t=(((count-l))/count)*100;
      if(t&lt;0)
        t=(-1)*t;
      printf("%.1lf\n",t);
    }
    count=0;
  }
  getch();
  return 0;
}
</code></pre>
