我编写了下面粘贴的代码,按照它们的说明顺序执行以下任务:
这是我的代码:
#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文件时,我不断收到错误消息:
在抛出'std :: bad_alloc'的实例后终止调用
what():std :: bad_alloc
中止(核心倾倒)
我已经收集了这与内存不足或变量从main()函数中脱落有关,但我无法弄清楚如何在这种特定情况下解决问题。如果它是相关的,我正在Linux计算机上工作。
发布于 2019-04-11 09:30:19
这段代码有3个洞:
第一个:int numEntries
。你以后做:++numEntries;
您增加未指定的值。不确定它是否是UB,但仍然很糟糕。
第二个和第三个:
const int length = numEntries;
int* arr = new int[length];
和
const int size = numEntries;
int matrix[size];
numEntries
有未指定的值(第一洞)。您可以使用它来初始化length
和size
-这是未定义的行为。但是我们假设它只是一些大数字 - 你分配未指定大小的内存(可能只是非常大的大小),因此std::bad_alloc
异常 - 这意味着你想分配更多你可用的内存。
另外,matrix
是VLA
未指定大小,这既是非标准和未定义的行为。
发布于 2019-04-11 09:56:18
对我来说,失去焦点1秒,花费30分钟的调试时间:
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没有将此显示为警告。
如果您使用源代码控制,经常提交,您将很容易找到它。
希望有所帮助。
https://stackoverflow.com/questions/-100009007
复制相似问题