更正2D阵列的内存分配/释放?

时间:2015-12-09 19:45:09

标签: c arrays malloc free realloc

我想知道是否正确分配和释放内存。我是否只分配了适量的内存? free()是否应该使用?在下一步中,我应该为具有更多行的数组重新分配内存...任何暗示realloc的外观如何?

#include <stdio.h>
#include <stdlib.h>

#define cols        2

int** allocArray (unsigned int cap)
{
int** p;
unsigned int i;
p = (int **)malloc(sizeof(p)*cap);
for (i=0;i<cap;i++) {
    *(p+i) = (int *)malloc(sizeof(*p)*cols);
}
return p;
}

void freeArray (int** p, unsigned int cap)
{
int i;
for (i=0;i<cap;i++) {
    free(*(p+i));
}
free(p);
}

int main(void)
{
int** arr;
unsigned int cap = 2;

arr = allocArray(cap);
freeArray(arr,cap); 

return 0;
}

非常感谢任何意见。

1 个答案:

答案 0 :(得分:1)

这不是一个真正的答案,但是评论太长了 - 特别是对于示例代码。

一个简单的优化是只对多维数组的整个数据区域进行一次分配,并根据需要为指向数据数组的指针创建数组。这将大大减少单独的内存分配数量 - 随着阵列大小的增加,这可能很重要。减少使用malloc()(或C {中的new)的动态分配数对于多线程应用程序来说也是非常重要的,因为即使对于目标分配器,内存分配也往往是单线程的。多线程使用。

你可以做一个只有两个分配的二维数组:

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 );
}

void free2dIntArray( int **array )
{
    free( array[ 0 ] );
    free( array );
}

您可以对任意数量的维度使用相同的技术,这样可以仅使用N个分配来分配N维数组。

如果你真的想要,你可以将分配数量减少到只有一个 - 但是你必须担心指针的大小和所有元素的对齐。