. Advertisement .
..3..
. Advertisement .
..4..
I encountered the following problem in completing my work:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
Below is the code I ran:
#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;
}
What’s causing it, and how can it be resolved in the “terminate called after throwing an instance of ‘std::bad_alloc’ what(): std::bad_alloc“ in the cpp?
The cause:
You have got this error because you are having 3 holes:
1st hole is
int numEntries
. Then you do:++numEntries;
You are increasing the undefined values. Even if it is UB, it’s still faulty.
2nd hole is:
3rd hole is:
numEntries
(first hole) has undetermined values. It is Specified Behavior when you use it to initializelength
andsize
. Thestd::bad alloc
error indicates that you are attempting to allocate more memories than is currently available. However, let’s assume that it is just a large number and that you are allocating memory of an indeterminate amount (perhaps just a very large value).Additionally, the behavior of the
matrix
, which is undefined and non-standard, is aVLA
of undefined size.These are the reasons of your error.
Solution:
You have to provide the specified values for
numEntries
,matrix
and give enough memories forstd::bad alloc
.Focus loss, 30 minutes wasted
As you can see, nV has not been initialized but is used in the constructor.
The nV takes garbage value for each run. This means that the program can sometimes work and crash when the garbage value (or garbage value) is too high.
Rextester didn’t crash, possibly due to some different initialization, https://rextester.com/l/cpp_online_compiler_gcc
This warning is not displayed by Apache Netbeans
We hope that this helps.