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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39935786/
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 14:52:35  来源:igfitidea点击:

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

c++

提问by 2good4this

I wrote the code pasted below to perform the following tasks in the order in which they are stated:

我编写了粘贴在下面的代码,以按照说明的顺序执行以下任务:

  1. Read an input file and count the number of entries in it
  2. Create an array of appropriate size (size equal to number of entries)
  3. Go back to the beginning of the input file and read it again
  4. Store the entries in an array
  5. Print out the number of entries in the file and the entries themselves.
  1. 读取输入文件并计算其中的条目数
  2. 创建一个适当大小的数组(大小等于条目数)
  3. 回到输入文件的开头,再读一遍
  4. 将条目存储在数组中
  5. 打印出文件中的条目数和条目本身。

Here is my code:

这是我的代码:

#include <iostream>
#include <fstream>
#include <exception>

using namespace std;

int main(int argc, char* argv[]){

    ifstream inFile(argv[1]); //passing arguments to the main function
    int numEntries;

    if(!inFile){
        cout << "file not found" << endl;
        return 1;
    }

    string entry;
    while (!inFile.eof()){ //counting the number of entries
        getline(inFile,entry);
        ++numEntries;
    }

    const int length = numEntries;  //making an array of appropriate length
    int*arr = new int[length];

    inFile.clear();             //going back to the beginning of the file
    inFile.seekg(0, ios::beg);

    int i = 0;
    const int size = numEntries;    //making an array to store the entries in the file
    int matrix[size];
    int pos = 0;

    int variable = 0;
    while(pos < size){
        inFile >> variable;
        matrix[pos] = variable;
        ++pos;
    }
    cout<< numEntries << "entries have been read"<< endl; 
    inFile.close();
    for(int i = 0; i < pos; ++i)
        cout << matrix[i] << endl; //printing out the entries
    return 0;
}

When I execute the .cpp file I keep getting the error message:

当我执行 .cpp 文件时,我不断收到错误消息:

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)

I have gathered this has to do with a memory shortage or variables falling out of the main() function, but I can not figure out how to address the problem in this specific situation. If it is relevant, I am working on a Linux computer.

我认为这与内存不足或变量从 main() 函数中掉出来有关,但我不知道如何在这种特定情况下解决问题。如果相关,我正在使用 Linux 计算机。

采纳答案by xinaiz

This code has 3 holes:

这段代码有3个洞:



First hole: int numEntries. Later you do: ++numEntries;

第一洞:int numEntries。稍后你会这样做:++numEntries;

You increment unspecified value. Not sure if it's UB, but still bad.

您增加未指定的值。不确定它是否是UB,但仍然很糟糕。



Second and third hole:

第二洞和第三洞:

const int length = numEntries;
int* arr = new int[length];

And

const int size = numEntries;
int matrix[size];

numEntrieshas unspecified value (first hole). You use it to initialize lengthand size- that is Undefined Behaviour. But let's assume it is just some big number - you allocate memory of unspecified size (possibly just very big size), hence the std::bad_allocexception - it means you want to allocate more memory that you have available.

numEntries具有未指定的值(第一个孔)。您可以使用它来初始化lengthsize-这是未定义的行为。但是让我们假设它只是一个大数字——你分配了未指定大小的内存(可能只是非常大的大小),因此std::bad_alloc例外——这意味着你想要分配更多可用的内存。

Also, matrixis VLAof unspecified size, which is both non-standard and Undefined behaviour.

另外,matrixVLA未指定大小,这既是非标准和未定义的行为。

回答by Manohar Reddy Poreddy

Loss of focus, wasted 30 mins:

注意力不集中,浪费了 30 分钟:

class Cls1{
    int nV;   //  <------------- nV is un-initialized
    vector<bool> v1;
public:
    Cls1 () {
        v1 = vector<bool> (nV + 1, false);  // <------------------ nV is used
    }
};

As you can see nV is un-initialized, but is used below in constructor.

如您所见,nV 未初始化,但在下面的构造函数中使用。

Since the nV took garbage value, different for each run, the program sometimes worked, and other times crashed when the nV garbage value is very high (garbage value)

由于nV取垃圾值,每次运行不同,程序有时运行,有时当nV垃圾值很高时崩溃(垃圾值)

  • Rextester didn't crash, possibly due to some different initialization, https://rextester.com/l/cpp_online_compiler_gcc

  • Apache Netbeans does not show this as warning

    • Having files under Git, you can see changes easily, will find these issue.
  • Reextester 没有崩溃,可能是由于一些不同的初始化,https://rextester.com/l/cpp_online_compiler_gcc

  • Apache Netbeans 不会将此显示为警告

    • 在 Git 下有文件,你可以很容易地看到变化,会发现这些问题。

Hope that helps.

希望有帮助。