I have a function which allocates memory for a 3d array. The goal is for the memory to be guaranteed contiguous but also have the convenience of a[k][j][i]
syntax:
double *** allocate_3d(const int& sz, const int& sy, const int& sx){
double * aMem = new double[sz*sy*sx];
double *** array = new double**[sz];
for(int k=0; k<sz; k++){
array[k] = new double*[sy];
for(int j=0; j<sy; j++){
array[k][j]= aMem + k*sy*sx + j*sx;
}
}
return array;
}
Supposing that I call the function like this
x = allocate_3d(wdz,wdy,wdx);
How can I properly deallocate x? I tried the following:
void delete_3d(double *** array, const int& sz, const int& sy, const int& sx){
for(int k=0; k<sz; k++){
for(int j=0; j<sy; j++){
delete[] array[k][j];
}
delete[] array[k];
}
delete[] array;
}
But running Valgrind gives an error and seems to indicate that the memory is not deallocated properly.
Should actually be like this:
void delete_3d(double *** array, const int& sz, const int& sy, const int& sx) {
// first, restore the pointer to the actual aMem
double * aMem = array[0][0];
// only one dimension was allocated in the loop,
// so only one loop should be deallocating things
for(int k = 0; k < sz; k++) {
delete [] array[k];
}
delete[] array;
delete[] aMem;
}
Wrap std::vector
to get both: contiguous memory and a reasonably simple access syntax and as a bonus no additional arrays which is better for memory, performance and maintenance:
class Array3d {
public:
Array3d(size_t sx, size_t sy, size_t sz)
: m_sx(sx), m_sy(sy) {
m_array.resize(sx * sy * sz);
}
// Can't overload operator[] with more that one parameter
// so we'll have to do with operator()
double &operator()(size_t x, size_t y, size_t z) {
size_t index = x * m_sx * m_sy + y * m_sy + z;
return m_array[index];
}
private:
size_t m_sx, m_sy;
std::vector<double> m_array;
};
Usage example:
Array3d array(3, 3, 3);
array(0, 1, 2) = 3.14;