繁体   English   中英

正确地为2D数组分配内存/取消内存分配?

[英]Correct memory allocation/deallocation for 2D array?

我想知道是否正确分配和释放内存。 我分配的内存量适中吗? 是否按原样使用了free()? 在下一步中,我应该为具有更多行的数组重新分配内存...任何提示如何重新分配会是什么样子?

#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维数组。

而且,如果您确实愿意,可以将分配数减少到只有一个-但是您必须担心指针的大小和所有元素的对齐。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM