如何在使用C语言的情况下释放内存而不使用free()?

2021年3月10日16:24:49 发表评论 640 次浏览

题:如何在不使用" free()"函数的情况下动态释放内存

解:标准库功能realloc()可用于取消分配先前分配的内存。下面是" stdlib.h"中" realloc()"的函数声明

void * realloc ( void *ptr, size_t size);

如果"大小"为零, 则对realloc的调用等效于" free(ptr)"。并且, 如果" ptr"为NULL并且大小不为零, 则对realloc的调用等效于" malloc(size)"。

让我们用一个简单的例子来检查。

/* code with memory leak */
#include <stdio.h>
#include <stdlib.h>
  
int main( void )
{
     int *ptr = ( int *) malloc (10);
  
     return 0;
}

使用valgrind工具检查泄漏摘要。它显示了10个字节的内存泄漏, 该泄漏被红色高亮显示。

[narendra@ubuntu]$ valgrind –leak-check=full ./free
  ==1238== LEAK SUMMARY:
  ==1238==    definitely lost: 10 bytes in 1 blocks.
  ==1238==      possibly lost: 0 bytes in 0 blocks.
  ==1238==    still reachable: 0 bytes in 0 blocks.
  ==1238==         suppressed: 0 bytes in 0 blocks.
[narendra@ubuntu]$

让我们修改上面的代码。

#include <stdio.h>
#include <stdlib.h>
  
int main( void )
{
     int *ptr = ( int *) malloc (10);
  
     /* we are calling realloc with size = 0 */
     realloc (ptr, 0);
     
  
     return 0;
}

检查valgrind的输出。它显示没有可能的内存泄漏, 以红色突出显示。

[narendra@ubuntu]$ valgrind –leak-check=full ./a.out
  ==1435== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
  ==1435== malloc/free: in use at exit: 0 bytes in 0 blocks.
  ==1435== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.
  ==1435== For counts of detected errors, rerun with: -v
  ==1435== All heap blocks were freed — no leaks are possible.
  [narendra@ubuntu]$

本文由" Narendra Kangralkar"编辑, 并由lsbin团队审阅。如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: