C内存分配和释放

时间:2015-05-14 12:42:41

标签: c memory-management

我编写了以下C函数,在必要的内存分配后返回一个双指针。

// integer double pointer to 2d array
void** idp_to_2d ( int rows , int cols ) {
    int i ;
    void **est = malloc ( rows * sizeof ( int* ) ) ;
    for ( i = 0 ; i <= rows ; i ++ )
        est[i] = malloc ( cols * sizeof (int ) ) ;
    return est ;
}

然后我使用main()中的以下代码接收此指针:

int **est = ( int** ) idp_to_2d ( rows , cols ) ;

它工作正常,我可以像est[i][j]那样索引,意味着内存分配正确。

现在我使用以下代码释放main()中的内存:

int i ;
for ( i = 0 ; i <= rows ; i ++ )
    free ( est[i] ) ;
free ( est ) ;

现在我得到双重免费或损坏错误。

我的编译器是 gcc 4.9.2 操作系统 Ubuntu 15.04 (64位)我正在使用 NetBeans IDE 8.0.2

1 个答案:

答案 0 :(得分:11)

您的for循环错误 - 您正在迭代太多行 - 更改:

for ( i = 0 ; i <= rows ; i ++ )
               ^^^

为:

for ( i = 0 ; i < rows ; i ++ )
               ^^^

malloc循环和free循环中。

<小时/> 此外,虽然这不是一个错误,但你应该真的改变:

void** idp_to_2d(...

为:

int** idp_to_2d(...

当然:

void **est = malloc(...

为:

int **est = malloc(...

因为函数返回int **而不是void **。 (在任何代码中使用void **都没有意义。)

您还可以删除返回值的冗余(并且可能是危险的)强制转换,因此:

int **est = ( int** ) idp_to_2d ( rows , cols ) ;

就是:

int **est = idp_to_2d ( rows , cols ) ;