[英]How to free 2d array in C?
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
?如何使用free
释放ptr
? Should I loop over ptr
and free ptr[i]
or should I just do我应该遍历ptr
和 free ptr[i]
还是应该这样做
free(ptr)
and ptr
will be freed?而ptr
会被释放吗?
You will have to loop over ptr[i]
, freeing each int*
that you traverse, as you first suggest.正如您首先建议的那样,您将不得不循环ptr[i]
,释放您遍历的每个int*
。 For example:例如:
for (int i = 0; i < N; i++)
{
int* currentIntPtr = ptr[i];
free(currentIntPtr);
}
Just the opposite of allocation:与分配正好相反:
for(int i = 0; i < N; i++)
free(ptr[i]);
free(ptr);
Yes, you must loop over ptr
and free each ptr[i]
.是的,您必须遍历ptr
并释放每个ptr[i]
。 To avoid memory leaks, the general rule is this: for each malloc()
, there must be exactly one corresponding free()
.为了避免内存泄漏,一般规则是:对于每个malloc()
,必须正好有一个对应的free()
。
while (N) free(ptr[--N]);
free(ptr);
#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 */
g_ptr_array_free()
for freeing arrays of pointers, g_ptr_array_free()
用于释放指针数组,g_strfreev()
for freeing arrays of strings. g_strfreev()
用于释放字符串数组。I find it hard to do any serious C programming without GLib.我发现没有 GLib 就很难进行任何严肃的 C 编程。 It introduces things such as dynamic strings and lays foundations for functional programming .它介绍了诸如动态字符串之类的东西,并为函数式编程奠定了基础。 It should really be part of the standard C run-time library.它真的应该是标准 C 运行时库的一部分。 It would give C a breath of fresh air.它会让 C 呼吸新鲜空气。 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).这将使 C在 2019 年再次成为一种合理且具有竞争力的语言。但由于它不是,它将为您的应用程序增加 1 MB(无论是 DLL 大小还是可执行文件大小)。 Also the Windows distribution is maintained by sadists .此外,Windows 发行版由虐待狂维护。
for(int i=0;i<N;i++) free(ptr[i]);
free(ptr);
you are not checking for malloc failure to allocate.您没有检查 malloc 分配失败。 You should always check.你应该经常检查。
void freeMatrix(int **matrix ,int row) { for(int i=0;i<row;i++) { free(matrix[i]); } free(matrix); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.