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 it's 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 let's 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.

Tags:

C++