简体   繁体   English

如何在以下代码中释放分配给malloc的内存?

[英]how to deallocate the memory allocated to the malloc in following code?

           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()的地方或在程序末尾)调用free() ?

With free . 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). 您必须首先释放arr[i]条目所指向的内存,然后最后释放arr (包含这些条目)所指向的内存。 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. 您无法反过来做,因为释放内存意味着您可能不再使用该内存中的值。

Thus: 从而:

for (i = 0; i < n; ++i) {
    free(arr[i]);
}
free(arr);
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. 顺便说一句,您应该确保分配没有失败,至少是arr分配失败,否则最终将取消对NULL指针的引用。

You have to loop through arr and free arr[i] , and then free arr when you are done. 您必须遍历arr和free arr[i] ,然后在完成后释放arr。 You need the same number of free calls as malloc calls. 您需要的免费呼叫数量与malloc呼叫相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM