This isn't really an answer, but it's too long for a comment - especially with the example code.
One easy optimization is to do just one allocation for the entire data area of a multi-dimensional array, and create arrays as necessary for the pointers into the data array. This will dramatically reduce the number of separate memory allocations - which can be important as the size of the array increases. Reducing the number of dynamic allocations that use malloc()
(or new
in C++) can also be extremely important for multithreaded applications as memory allocations tend to be single-threaded to a very large degree even for allocators targeted for multithreaded use.
You can do a 2-dimensional array with only two allocations:
int **alloc2IntArray( size_t m, size_t n )
{
// get an array of pointers
int **array = malloc( m * sizeof( *array ) );
if ( NULL == array ) // I do this in case I mistype "==" as "="
{
return( NULL );
}
// get the actual data area of the array
// (this gets all rows in one allocation)
array[ 0 ] = malloc( m * n * sizeof( **array ) );
if ( NULL == array[ 0 ] )
{
free( array );
return( NULL );
}
// fill in the array of pointers
// start at 1 because array[ 0 ] already
// points to the 0th row
for ( size_t i = 1U; i < m; i++ )
{
// use extra parenthesis to make it
// clear what's going on - assigning the
// address of the start of the i-th
// row in the data area that array[ 0 ]
// points to into the array of pointers,
// which array points to (array[ 0 ]
// already points to the 0th row)
array[ i ] = &( ( array[ 0 ] )[ i * n ] );
}
return( array );
}
and
void free2dIntArray( int **array )
{
free( array[ 0 ] );
free( array );
}
You can use the same technique for an arbitrary number of dimensions, such that an N-dimensional array can be allocated with just N allocations.
And if you really want to, you can reduce the number of allocations down to just one - but then you have to worry about size of pointers and the alignment of all the elements.