Your understanding of bad_alloc
is slightly incorrect. bad_alloc
is thrown by the new operator when it fails to allocate the requested amount of memory. It is not uncommon to see this happening if you send extremely large values to new
.
For example, this could happen if suma
would not be initialized.
You should turn on first-time exception handling in your debugger (catch throw
in gdb) and verify where the exception is thrown and what amount of memory your program is requesting.
What you might be observing is an invalid memory reference. You could replace your code to use std::vector
and using the at()
method to access the elements. This will throw you an exception if you incorrectly access an out-of-range element.
Alternatively, add an assert like this:
#include<cassert>
...
const int idx = i * rowWidth + j;
assert(idx >= 0);
assert(idx < suma);
possible[idx] = j;
If the assertion triggers (it probably will) you will now have confirmed that either your array is too small or your index is invalid.