how to solve std::bad_alloc?

Hi, Folks,

I need a program to solve a PDE numerically. I first wrote a smaller program which worked very well. After extending the program I receive now exception which says "std::bad_alloc".

The offending line comes from a function lu_solver() I wrote. The line should allocate memory dynamically. I read a bit about std::bad_alloc. It should be thrown if memory cannot be allocated. But this function worked perfectly well in the first program before. The only change is that the function lu_solver() was called upon directly before and it is called by another function now. I attach only a part of the code because the whole program is too long.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void lu_solver(double a[], double b[], double c[], double uu[], double xx[], double q[], int Dim)

   {
	   
	  double *y = new double[Dim]; 
	   y[0] = q[0];

	   for(int ii=1; ii<Dim; ii++)
	   y[ii] = q[ii] - b[ii-1]*y[ii-1]/uu[ii-1];
	   
	   
	   xx[Dim-1] = y[Dim-1]/uu[Dim-1]; //starting element of backward sweeping

	   for(int ii=Dim-2; ii>=0; ii--)
	   xx[ii] = (y[ii]-c[ii]*xx[ii+1])/uu[ii];  

	   delete [] y; 	  
  }


The line provoking exception is underscored. Thank you for any suggestion.
Last edited on
Unfortunately, that doesn't really help to answer the problem.

How is your program using the memory? Are you trying to allocate some huge Dim at some point? (Or negative? Or Zero?) Are you trying to use lu_solver() a whole lot of times? Etc.

You can catch() the error by wrapping the new statement in a try..catch block...
1
2
3
4
5
6
7
8
9
10
11
12
13
double *y;
try {
  y = new double[Dim];
  }
catch (std::bad_alloc e)
  {
  cerr << "lu_solver() bad_alloc: " << e.what() << endl;
  cerr << "Dim=" << Dim << endl;
  return;
  }

y[0] = q[0];
...

This code just stops the program from crashing, but it doesn't tell you anything about why you ran out of memory.

Good luck!
Thank you, Duoas, for the reply.

I am not really aware how I am using the memory. The int Dim is always positive and of the order of several thousand. But lu_solver() is called repeatedly, about ten thousand times. I thought if I deleted y every time after using there would be no memory problem.
Topic archived. No new replies allowed.