Allocation failure 2 in matrix() in nrutil.h


pkiskool
05-27-2008, 10:09 AM
Hi,

Could someone explain what is going on when run-time error of "allocation failure 2 in matrix ()" appears - in nrutil.h?

I'm using lubksb and ludcmp to solve matrices.
It worked when I was solving just ONE matrix, but I needed to loop my code and continuously update the matrix that I need to solve and then send it to lubksb and ludcmp for the solution.
The error caused after I looped it and added a few sub-functions that updates the matrix.

Just a general explanation on the error would be nice as well.

Thank you.

davekw7x
05-27-2008, 02:02 PM
Could someone explain what is going on when run-time error of "allocation failure 2 in matrix ()" appears - in nrutil.h?


Are you still using C versions of nrutil and nr with your C++ program? (There are huge advantages in using C++ versions of Numeric Recipes library in C++ programs, but you are probably too far along in your project to change now, and, if everything else is satisfactory... Oh, well.)

Anyhow, for the C version:

The built-in error handler called inside the nrutil function matrix() prints that message when it can't get the amount of memory that you have requested from the system.

If the matrices are all of the same size, then just call matrix() once (before you get into the loop).

If they are different sizes, then call matrix() inside the loop (after you find out what size you need for that time through the loop), and be sure to call free_matrix() at the end of the loop (or any time before the next call to matrix().

Example of a 10000x10000 matrix called 100 times:



/* Put your #include stuff here for nr.h, nrutil.h, etc. */
int main()
{
int NP = 10000; // Doesn't have to be constant; can change if need be

int i;
float ** a;
int count;

count = 0;
for (i = 0; i < 100; i++) {
// Note that if your program needs to change NP, it's ok here
a = matrix(1, NP, 1, NP);
++count;
//
// Do whatever you need to do with matrix a
//
free_matrix(a, 1, NP, 1, NP); // Same value of NP used for call to matrix()
}
printf("After loop1: count = %d\n\n", count);

count = 0;
for (i = 0; i < 100; i++) {
a = matrix(1, NP, 1, NP);
++count;
printf("count = %d\n", count);
//
// Do whatever you need to do with matrix a
//
}
printf("After loop2: count = %d\n\n", count);

return 0;
}



Output on my Linux system (g++ 4.1.2)

After loop1: count = 100

count = 1
count = 2
count = 3
count = 4
count = 5
count = 6
count = 7
Numerical Recipes run-time error...
allocation failure 2 in matrix()
...now exiting to system...

Output with various Windows compilers (on Windows XP) was about the same, but it only got up to count = 3 or 4 before bailing out.

If this doesn't help, then show us the loop where your program is getting into trouble.

Regards,

Dave