C++ 错误:抛出“std::bad_alloc”实例后调用终止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23444844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:26:53  来源:igfitidea点击:

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

c++memory-managementruntime-error

提问by andressophia

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".

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

I have RectInvoice class and Invoice class.

我有 RectInvoice 类和 Invoice 类。

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?

我想在 eclipse.ini 文件中更改 eclipse 内存。但是我没有授权,我该怎么做?

回答by Agus Arias

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, &rectis a temporary address (stored in the function's activation registry) and will be destroyed when that function end.

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

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

干杯

回答by Christian Hackl

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

有些东西会抛出一个 type 异常std::bad_alloc,表明你的内存不足。此异常通过 until 传播main,在那里它“脱离”您的程序并导致您看到的错误消息。

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w hlooks like a syntax error.

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