我编写了下面粘贴的代码,以按照说明的顺序执行以下任务:
- 读取输入文件并计算其中的条目数
- 创建适当大小的数组(大小等于条目数)
- 返回到输入文件的开头并再次读取
- 将条目存储在数组中
- 打印出文件中的条目数以及条目本身。
这是我的代码:
#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 文件时,我不断收到错误消息:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
我认为这与内存短缺或变量脱离 main() 函数有关,但我不知道如何在这种特定情况下解决问题。如果相关的话,我正在 Linux 计算机上工作。
这段代码有3个漏洞:
第一个洞:int numEntries
。稍后你会:++numEntries;
您增加未指定的值。不确定是不是UB,但还是很糟糕。
第二、三号洞:
const int length = numEntries;
int* arr = new int[length];
And
const int size = numEntries;
int matrix[size];
numEntries
具有未指定的值(第一个孔)。你用它来初始化length
and size
- 那是未定义的行为。但是让我们假设它只是一些大数字 - 您分配未指定大小的内存(可能只是非常大的大小),因此std::bad_alloc
异常 - 这意味着您想要分配更多可用内存。
Also, matrix
is VLA
大小未指定,这既是非标准行为,也是未定义的行为。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)