C语言 如何在以下代码中释放分配给 malloc 的内存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4330770/
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
how to deallocate the memory allocated to the malloc in following code?
提问by thetna
int n;
int **arr;
arr = (int**)malloc(n*sizeof(int));
for (i=0; i<n; ++i){
arr[i] = malloc(2*sizeof(int));
}
[EDIT]
[编辑]
*** glibc detected *** ./abc: double free or corruption (out): 0x0000000002693370
======= Backtrace: =========
/lib/libc.so.6(+0x775b6)[0x7f42719465b6]
/lib/libc.so.6(cfree+0x73)[0x7f427194ce53]
./abc[0x405f01]
/lib/libc.so.6(__libc_start_main+0xfd)[0x7f42718edc4d]
./abc[0x400ee9]
======= Memory map: ========
00400000-00416000 r-xp 00000000 08:07 392882
00616000-00617000 r--p 00016000 08:07 392882
I tried with the following mentioned answers, But i got the following above mentioned error.What can be the reason for it?
我尝试了以下提到的答案,但出现了上述错误。可能是什么原因?
[EDIT]
[编辑]
The above mentioned problem is now solved. Since there was bug in the code. Now,what i am not getting is any improvement in the freed memory.What can be the reason for it?
上面提到的问题现在已经解决了。由于代码中有错误。现在,我没有得到释放内存的任何改善。这可能是什么原因?
[EDIT] I am using some modules to print the memory.following is the code
[编辑] 我正在使用一些模块来打印内存。以下是代码
memory_Print();
#ifdef CHECK
memory_PrintLeaks();
#endif
Here memory_PrintLeaks()prints the demanded memory and freed memory.I am getting the same value after making the changes.
这里memory_PrintLeaks()打印了所需的内存和释放的内存。进行更改后我得到了相同的值。
One more remark what i would like to add is, can i call the free() anywhere from the program or it is required to call from some particular locations like the place where the malloc() has been called or at the end of the program?
我想补充的另一句话是,我可以从程序的任何地方调用 free() 还是需要从某些特定位置调用,例如调用 malloc() 的地方或程序结束时?
回答by Karl Knechtel
With free. You must first free the memory pointed at by the arr[i]entries, and then finally free the memory pointed at by arr(which holds those entries). You can't do it the other way around, because freeing memory means you may no longer use the values that were in that memory.
与free. 您必须首先释放arr[i]条目指向的内存,然后最后释放 指向的内存arr(保存这些条目)。你不能反过来做,因为释放内存意味着你可能不再使用该内存中的值。
Thus:
因此:
for (i = 0; i < n; ++i) {
free(arr[i]);
}
free(arr);
回答by EboMike
for (i=0; i<n; ++i){
free(arr[i]);
}
free(arr);
Btw, you should make sure that your allocations didn't fail, at least the one for arr, or else you would end up dereferencing NULL pointers.
顺便说一句,你应该确保你的分配没有失败,至少是 for arr,否则你最终会取消引用 NULL 指针。
回答by Lou Franco
You have to loop through arrand free arr[i], and then free arr when you are done. You need the same number of free calls as malloc calls.
您必须循环遍历arr和 free arr[i],然后在完成后释放 arr 。您需要与 malloc 调用相同数量的免费调用。

