Hi friends,

I wrote a code to build a matrix with specific calculations. When I'm using 3000 elements works well ... But I did a test with 150.000 (150.000 x 150.000) and I had problems.

" terminate called after throwing an instance of 'std::bad_alloc' "


I'm copying the code part of the problem:

void buildMatrix(ofstream &myfileOutSubsetZ, ofstream &myfileOutSubset,ofstream &myfileOut,ofstream &myfileLog,vector<string> &vetorInd)
{
	float **AAA = 0;
	AAA = new float *[vetorInd.size()];
	for(int i=0;i<vetorInd.size();i++)
		AAA[i]= new float [vetorInd.size()]; // PROBLEM!
        ...

Can you help me please?

Cheers!

Because 150.000 x 150.000 floats equals ~21GB of memory.
I don't think you have that much RAM in your computer.

The new operator throws an exception of std::bad_alloc if the allocation fails.

[rhetorical question]
Did you catch the exception?
[/rhetorical question]

Thanks Insensus and Narue!

Narue, No ... I didn't take the exception. I don't know ho to do this. Is it simple?

Cheers

Narue, is it correct?

try
	{
		for(int i=0;i<vetorAni.size();i++)
				A[i]= new float [vetorAni.size()];


	}catch(bad_alloc)
	{
		cout << "Exception raised: " << bad_alloc << '\n';
	}

Narue,

I tried this one but I couldn't take the message ... :(

try
    {
        for(int i=0;i<vetorAni.size();i++)
                A[i]= new float [vetorAni.size()];
    }catch(char * str)
    {
        myfileLog << "\nException raised: " << str << endl;
    }

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Okay, instead of just guessing and writing random stuff, go read a C++ reference on handling exceptions. Or search google. Of course, there's still the issue of trying to allocate exorbitant amounts of memory.

Comments
It was an easy walk to get past AD, now for the long climb to the #1 spot

The exception that happened is "St9bad_alloc".

Can you help me?

The problem is clear, and has been answered already. std::bad_alloc is the exception that is thrown when dynamic memory allocation fails. Generally, the most likely reason why dynamic allocation can fail is because it would require more memory than you have available on your computer. When allocating a 150,000 x 150,000 array, it comes to no surprise that you run out of memory, that's about 84 Gb (I think that a system which can produce or at least emulate 84Gb of contiguous RAM memory is very rare).

Try to avoid needing such a large amount of memory at once in your program.

BTW, to catch the exception, you do:

#include <iostream>

int main() {
  try {
    float * huge_array = new float[150000 * 150000];
    //...
    delete huge_array;
  } catch(std::bad_alloc& e) {
    std::cout << "Could not allocate the required memory, failed with error: '" << e.what() << "'" << std::endl;
    return 1;
  };
  return 0;
};

Edited 5 Years Ago by mike_2000_17: n/a

This question has already been answered. Start a new discussion instead.