C语言 如何释放c 2d数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5666214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:24:00  来源:igfitidea点击:

how to free c 2d array

cmemory-management

提问by lina

i have the following code:

我有以下代码:

int **ptr = (int **)malloc(sizeof(int*)*N); 
for(int i=0;i<N;i++) 
     ptr[i]=(int*)malloc(sizeof(int)*N));

how can i free ptr using free? should i loop over ptr and free ptr[i]? or just do

我怎样才能免费使用 ptr free?我应该遍历 ptr 和 free ptr[i] 吗?或者只是做

free(ptr) 

and ptr will be freed?

而ptr会被释放吗?

采纳答案by James Bedford

You will have to loop over ptr[i], freeing each int* that you traverse, as you first suggest. For example:

正如您首先建议的那样,您将不得不遍历 ptr[i],释放您遍历的每个 int*。例如:

for (int i = 0; i < N; i++)
{
    int* currentIntPtr = ptr[i];
    free(currentIntPtr);
}

回答by Donotalo

Just the opposite of allocation:

与分配正好相反:

for(int i = 0; i < N; i++)
    free(ptr[i]);
free(ptr);

回答by Rob?

Yes, you must loop over ptrand free each ptr[i]. To avoid memory leaks, the general rule is this: for each malloc(), there must be exactly one corresponding free().

是的,您必须循环ptr并释放每个ptr[i]. 为避免内存泄漏,一般规则是:对于每个malloc(),必须恰好有一个对应的free()

回答by Srikanth

for(int i=0;i<N;i++) free(ptr[i]);
free(ptr);

you are not checking for malloc failure to allocate. You should always check.

您没有检查 malloc 分配失败。你应该经常检查。

回答by 7vujy0f0hy

Simple

简单的

while (N) free(ptr[--N]);
free(ptr);

Handsome

英俊的

#define FALSE 0
#define TRUE 1
typedef int BOOL;

void freev(void **ptr, int len, BOOL free_seg) {
    if (len < 0) while (*ptr) {free(*ptr); *ptr++ = NULL;}
    else while (len) {free(ptr[len]); ptr[len--] = NULL;}
    if (free_seg) free(ptr);
}

freev(ptr, N, TRUE); /* if known length */
freev(ptr, -1, TRUE); /* if NULL-terminated */
freev(ptr, -1, FALSE); /* to keep array */

Patrician

贵族

GLibfunctions:

GLib函数:

I find it hard to do any serious C programming without GLib. It introduces things such as dynamic stringsand lays foundationsfor functional programming. It should really be part of the standard C run-time library. It would give C a breath of fresh air. It would make C a reasonable and competitive language again for the year 2019.But because it isn't, it will add 1 MB to your application (either in DLL size or in executable size). Also the Windows distribution is maintained by sadists.

我发现没有 GLib 就很难进行任何严肃的 C 编程。它介绍了诸如动态字符串之类的东西,并为函数式编程奠定了基础。它真的应该是标准 C 运行时库的一部分。它会让 C 呼吸新鲜空气。这将使 C在 2019 年再次成为一种合理且具有竞争力的语言但由于它不是,它将为您的应用程序增加 1 MB(无论是 DLL 大小还是可执行文件大小)。此外,Windows 发行版由虐待狂维护