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

2go*_*his 7 c++

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

  1. 读取输入文件并计算其中的条目数
  2. 创建一个适当大小的数组(大小等于条目数)
  3. 返回输入文件的开头并再次阅读
  4. 将条目存储在数组中
  5. 打印出文件中的条目数以及条目本身。

这是我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

抛出'std :: bad_alloc'实例后调用终止
what():std :: bad_alloc
中止(核心已弃用)

我已经收集到这与内存不足或main()函数掉出的变量有关,但是我无法弄清楚在这种特定情况下如何解决该问题。如果相关,我正在Linux计算机上工作。

xin*_*aiz 6

这段代码有3个孔:


第一个孔:int numEntries。稍后您执行:++numEntries;

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


第二和第三个孔:

const int length = numEntries;
int* arr = new int[length];
Run Code Online (Sandbox Code Playgroud)

const int size = numEntries;
int matrix[size];
Run Code Online (Sandbox Code Playgroud)

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

而且,matrixVLA的大小不确定,既是非标准行为,又是未定义行为。


Man*_*ddy 6

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

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

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

由于 nV 取垃圾值,每次运行都不同,因此当 nV 垃圾值非常高(垃圾值)时,程序有时可以工作,有时会崩溃

  • Rextester 没有崩溃,可能是由于一些不同的初始化,https://rextester.com/l/cpp_online_compiler_gcc

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

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

希望有帮助。