In c++ a bad_alloc happen while assigning memory, or at least that was what I understood, but now I get this error while reading memory from an array. I create the array:
int * possible = new int[ suma ];
and then i got two for cycles, where I access the whole array:
for( int i = 0; i < n - 1; i++ ){
int rowWidth = (i - 1) < 0 ? 0 : permutationsNumber[i];
for( int j = 0; j < permutationsNumber[i]; j++ ){
possible[i * rowWidth + j ] = j;
}
}
for( int i = 0; i < n - 1; i++ ){
int rowWidth = (i - 1) < 0 ? 0 : permutationsNumber[i];
for( int j = 0; j < permutationsNumber[i]; j++ ){
std::cout << possible[i * rowWidth + j ] << "\n";
}
In the second for in the line std::cout << possible[i * rowWidth + j ] << "\n";
is where i got the error.
I compile the code on Windows, tried using 3 different machines with windows 8 and 7, using VS 2010, 2012 and 2013 and got the same error.
When I compile the code on Mac i got no error, same using compileonline
The variable values I didn't think as important are:
n = 4;
permutationsNumber = {4, 12, 24};
suma = 40;
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.