I want to use dynamically allocated data, corresponding to a 3D array in a C program. After using the data, I would like to properly deallocate the data again.
My approach is as follows:
#include <stdlib.h>
#include <stdio.h>
double ***arr3D_d( size_t dim1, size_t dim2, size_t dim3 ) {
size_t ii, jj;
double ***arr;
arr = calloc( (size_t)dim1, sizeof(double**) );
for ( ii=0 ; ii < dim1 ; ++ii ) {
arr[ii] = calloc( (size_t)(dim1*dim2*dim3), sizeof(double*) );
for ( jj=0 ; jj < dim2 ; ++jj) {
arr[ii][jj] = calloc( (size_t)(dim2*dim3), sizeof(double) );
}
}
return arr;
}
void free_arr3D_d( double ***arr, size_t dim1, size_t dim2 ) {
size_t ii, jj;
for( ii=0 ; ii<dim1 ; ++ii ) {
for ( jj=0 ; jj<dim2 ; ++jj ) {
free( arr[ii][jj] );
}
free( arr[ii] );
}
free( arr );
}
int main( int argc, char *argv[] ) {
size_t ii, jj, kk,
dim1, dim2, dim3;
double ***arr3D;
dim1 = 2;
dim2 = 3;
dim3 = 4;
arr3D = arr3D_d( dim1, dim2, dim3);
for ( ii=0 ; ii<dim1 ; ++ii)
for ( jj=0 ; jj<dim2 ; ++jj)
for ( kk=0 ; kk<dim3 ; ++kk)
printf( "arr3D[%ld][%ld][%ld] = %f (address: %p)\n",
ii, jj, kk, arr3D[ii][jj][kk],
(void*)&arr3D[ii][jj][kk] );
free_arr3D_d( arr3D );
return 0;
}
Compiling with gcc -Wall gives no errors and the code runs fine. Compiling with gcc -g and then testing with valgrind tells me that all memory is free'd.
So, everything seems to be fine. But, to be honest, I am not sure if I did the memory allocation part in a "good" way, as I don't understand it fully...
Any comments on my implementation are greatly appreciated.
Update1: I've just realized that there was an error in ***arr3D_d. Fixing the bug, and adding some error check, it should read as follows
double ***arr3D_d( size_t dim1, size_t dim2, size_t dim3 ){
size_t ii, jj;
double ***arr;
arr = calloc( (size_t)dim1, sizeof(double**) );
if (arr == NULL) {
fprintf( stderr, "cannot allocate memory, probably because out of memory\n" );
exit(0);
}
for ( ii=0 ; ii<dim1 ; ++ii ) {
arr[ii] = calloc( (size_t)(dim2*dim3), sizeof(double*) );
if (arr[ii] == NULL) {
fprintf( stderr, "cannot allocate memory, probably because out of memory\n" );
exit(0);
}
for ( jj=0 ; jj<dim2 ; ++jj ) {
arr[ii][jj] = calloc( (size_t)(dim3), sizeof(double) );
if (arr[ii][jj] == NULL) {
fprintf( stderr, "cannot allocate memory, probably because out of memory\n" );
exit(0);
}
}
}
return arr;
}