如何以这种方式释放C初始分味的Malloc 2D阵列?

发布于 2025-01-22 02:14:52 字数 276 浏览 2 评论 0原文

我在C中宣布了这样的2D Malloc数组:

    int** pArray;
    int i;

    pArray=(int**)malloc(pRows*sizeof(int*));
       for(i=0;i<pRows;i++)
         (int*)malloc(pColumns*sizeof(int*));

我该如何释放此数组?我在网上看到,free()的数量应与使用的malloc()数量相同。在这种情况下,我可以两次释放什么?

I have declared a 2D malloc array like this in C:

    int** pArray;
    int i;

    pArray=(int**)malloc(pRows*sizeof(int*));
       for(i=0;i<pRows;i++)
         (int*)malloc(pColumns*sizeof(int*));

How can I free this array? I saw on the net that the number of free() should be same as number of malloc() used. What can I free twice in this case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱花落人离去 2025-01-29 02:14:52

对于初学者来说,分配不正确。该语句

(int*)malloc(pColumns*sizeof(int*));

产生内存泄漏。

似乎您的意思是

int** pArray;
int i;

pArray = (int**)malloc( pRows * sizeof( int* ) );
for( i = 0; i < pRows; i++ )
{
     pArray[i] = (int*)malloc( pColumns * sizeof( int ) );
}

要注意以下代码在循环中的语句中使用sizeof(int)而不是size> sizeof(int *)

您需要以相反的顺序释放分配的内存

for( i = 0; i < pRows; i++ )
{
     free( pArray[i] );
}
free( pArray );

For starters the allocation is incorrect. This statement

(int*)malloc(pColumns*sizeof(int*));

produces a memory leak.

It seems you mean the following code

int** pArray;
int i;

pArray = (int**)malloc( pRows * sizeof( int* ) );
for( i = 0; i < pRows; i++ )
{
     pArray[i] = (int*)malloc( pColumns * sizeof( int ) );
}

Pay attention to that in the statement within the loop there is used the expression sizeof( int ) instead of sizeof( int * ).

You need to free the allocated memory in the reverse order

for( i = 0; i < pRows; i++ )
{
     free( pArray[i] );
}
free( pArray );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文