Chris Chris - 11 months ago 75
C++ Question

'std::bad_alloc' in array declaration in root(CERN), depending on array size

I have a piece of code that declares a 3D array of floats that inconsistently compiles.

void ImageCombine()

float *doseArrayTotal = new float[2350][2350][2350];
float *doseArray1 = new float[1175][1175][1175];
// I have commented out the rest of my code whilst debugging.

If doseArray1 is given dimensions [2350][2350][2350] or [1024][1024][1024], it will compile. Given the dimensions above [1175][1175][1175] or [1000][1000][1000] it will produce the error.

terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc

The way I am running this code is through a piece of software called root (terrible name) developed by CERN, and the input I provide to run this function is.

[co@fastpc11 mysim]$ root
root [0] .L ImageCombine.C
root [1] ImageCombine()

Any advice as to why my code wont run, and how I might be able to solve this would be greatly appreciated.


Answer Source

The originally posted code is not valid C++; it just happened to run when interpreted by CERN Root. To dynamically declare a 3D array:

float*** doseArrayTotal = new float**[2350];
for(int i = 0; i < 2350; ++i){
  doseArrayTotal[i] = new float*[2350];
  for(int j = 0; j < 2350; ++j){
    doseArrayTotal[i][j] = new float[2350];

To do the same using vectors:

vector<vector<vector<float> > > doseArrayTotal;
for (int i = 0; i < 2350; ++i) {
  for (int j = 0; j < 2350; ++j){

These two objects now work as 3D matrices or images, and a float can be stored or accessed at the position (1,2,3) for example by:

float ValueEntered = 7.3;
float ValueExtracted;
doseArrayTotal[1][2][3] = ValueEntered;
ValueExtracted = doseArrayTotal[1][2][3];