C++ error: terminate called after throwing an instance of std::bad_alloc
C++ error: terminate called after throwing an instance of std::bad_alloc
This code has 3 holes:
First hole: int numEntries
. Later you do: ++numEntries;
You increment unspecified value. Not sure if its UB, but still bad.
Second and third hole:
const int length = numEntries;
int* arr = new int[length];
And
const int size = numEntries;
int matrix[size];
numEntries
has unspecified value (first hole). You use it to initialize length
and size
– that is Undefined Behaviour. But lets assume it is just some big number – you allocate memory of unspecified size (possibly just very big size), hence the std::bad_alloc
exception – it means you want to allocate more memory that you have available.
Also, matrix
is VLA
of unspecified size, which is both non-standard and Undefined behaviour.
Loss of focus, wasted 30 mins:
class Cls1{
int nV; // <------------- nV is un-initialized
vector<bool> v1;
public:
Cls1 () {
v1 = vector<bool> (nV + 1, false); // <------------------ nV is used
}
};
As you can see nV is un-initialized, but is used below in constructor.
Since the nV took garbage value, different for each run, the program sometimes worked, and other times crashed when the nV garbage value is very high (garbage value)
- Rextester didnt crash, possibly due to some different initialization, https://rextester.com/l/cpp_online_compiler_gcc
- Apache Netbeans does not show this as warning
- Having files under Git, you can see changes easily, will find these issue.
Hope that helps.
C++ error: terminate called after throwing an instance of std::bad_alloc
Related posts on C++ ErrorĀ :
- Can you pop from a vector C++?
- What does getline () do in C++?
- How do I find a value in a vector C++?
- How do you create a blank vector in C++?
- What is fixed in Setprecision C++?
- Can you use Push_back in string C++?
- What is the use of climits in C++?
- How do you set set size in C++?
- How do you substring a string in C++?