首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C ++错误:抛出'std :: bad_alloc'实例后调用terminate

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

Stack Overflow用户
提问于 2019-04-11 00:32:15
回答 2查看 0关注 0票数 0

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

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

这是我的代码:

代码语言:javascript
复制
#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;
}

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

代码语言:javascript
复制
在抛出'std :: bad_alloc'的实例后终止调用
what():std :: bad_alloc
中止(核心倾倒)

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

EN

回答 2

Stack Overflow用户

发布于 2019-04-11 09:30:19

这段代码有3个洞:

第一个:int numEntries。你以后做:++numEntries;

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

第二个和第三个:

代码语言:javascript
复制
const int length = numEntries;
int* arr = new int[length];

代码语言:javascript
复制
const int size = numEntries;
int matrix[size];

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

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

票数 0
EN

Stack Overflow用户

发布于 2019-04-11 09:56:18

对我来说,失去焦点1秒,花费30分钟的调试时间:

代码语言:javascript
复制
class Cls1{
    int nV;   //  <------------- nV is un-initialized
    vector<bool> v1;
public:
    Cls1 () {
        v1 = vector<bool> (nV + 1, false);  // <------------------ nV is used
    }
};

如您所见,nV未初始化,但在构造函数中使用。 由于nV占用垃圾值,每次运行都不同,程序有时会工作,并且当nV垃圾值非常高时有时会崩溃。

我不想在我编写的程序中使用v1但是在将来的程序中,所以我甚至没有调查它。

暂时,直到我解决了问题,我转移到了一个在线编译器,它没有崩溃,可能是由于一些不同的初始化,https://rextester.com/l/cpp_online_compiler_gcc

第二天,我重新看了一下程序,它是构造函数的第一行,一个未使用的变量,导致了这个问题,不知道为什么Apache Netbeans没有将此显示为警告。

如果您使用源代码控制,经常提交,您将很容易找到它。

希望有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100009007

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档