C++错误:抛出'std :: bad_alloc'实例后调用terminate

and*_*hia 22 c++ memory-management runtime-error

我在eclipse上使用下面的代码,我得到一个错误终止"在抛出'std :: bad_alloc'的实例后调用what():std :: bad_alloc".

我有RectInvoice类和Invoice类.

class Invoice {
public:

    //...... other functions.....
private:
   string name;
   Mat im;
   int width;
   int height;
   vector<RectInvoice*> rectInvoiceVector; 
};
Run Code Online (Sandbox Code Playgroud)

我在Invoice的方法中使用下面的代码.

        // vect : vector<int> *vect;

        RectInvoice rect(vect,im,x, y, w ,h);
        this->rectInvoiceVector.push_back(&rect);
Run Code Online (Sandbox Code Playgroud)

我想在eclipse.ini文件中更改eclipse内存.但我没有授权这个.我怎么能这样做?

小智 22

您的代码中的问题是您不能在全局变量中存储局部变量的内存地址(例如,函数的本地变量):

RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
Run Code Online (Sandbox Code Playgroud)

在那里,&rect是一个临时地址(存储在函数的激活注册表中),并在该函数结束时被销毁.

代码应该创建一个动态变量:

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

在那里,您使用的堆地址在函数执行结束时不会被销毁.告诉我它是否适合你.

干杯

  • 如果不再需要,请不要忘记“删除”每个元素。 (2认同)

Chr*_*ckl 16

某些东西抛出了类型异常std::bad_alloc,表明你的内存不足.此异常会一直传播,直到main它"脱落"您的程序并导致您看到的错误消息.

由于这里没有人知道"RectInvoice","rectInvoiceVector","vect","im"等是什么,我们无法告诉你究竟是什么导致了内存不足的情况.您甚至没有发布您的真实代码,因为w h看起来像语法错误.