正确的二维数组内存分配/解除分配?

标签 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;
}

非常感谢任何输入。

最佳答案

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

一个简单的优化是只对多维数组的整个数据区域进行一次分配,并根据需要为指向数据数组的指针创建数组。这将显着减少单独内存分配的数量——随着数组大小的增加,这可能很重要。减少使用 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 次分配。

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

关于正确的二维数组内存分配/解除分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34187660/

相关文章:

java - 如何使用以下代码基于实例变量按升序对对象数组进行排序

javascript - 如何从动态生成的 Json 对象中删除值

c - 动态分配结构数组

c - C 中数据输入和 malloc 的问题

C 输入问题

C 递增/递减运算符

c++ - 是否可以使用位域数组?

c - 调整动态结构数组大小时,是否需要在我的结构中复制动态内存?

c - 结构初始化性能

python - Python-then-profile-then-C 设计模式的最佳实践?