C++ error : terminate called after throwing an instance of 'std::bad_alloc'

andressophia picture andressophia · May 3, 2014 · Viewed 131.8k times · Source

I use below code on eclipse and I get an error terminate "called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc".

I have RectInvoice class and Invoice class.

class Invoice {
public:

    //...... other functions.....
private:
   string name;
   Mat im;
   int width;
   int height;
   vector<RectInvoice*> rectInvoiceVector; 
};

And I use below code on a Invoice's method.

        // vect : vector<int> *vect;

        RectInvoice rect(vect,im,x, y, w ,h);
        this->rectInvoiceVector.push_back(&rect);

And I want to change eclipse memory in eclipse.ini file. But I dont authorized for this.How can I do this?

Answer

Agus Arias picture Agus Arias · Jan 7, 2015

The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);

There, &rect is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

The code should create a dynamic variable:

RectInvoice *rect =  new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);

There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.

Cheers