吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → 如何在不使用 C 中的 free() 的情况下释放内存

如何在不使用 C 中的 free() 的情况下释放内存

来源:网络 | 更新时间:2022-01-23 07:46:26
问题:如何在不使用“free()”函数的情况下动态解除分配内存。 解决方案:标准库函数realloc()可用于释放先前分配的内存。下面是“stdlib.h”中“realloc()”的函数声明
void *realloc(void *ptr, size_t size);
如果“size”为零,则调用 realloc 等价于“free(ptr)”。如果“ptr”为 NULL 且 size 不为零,则调用 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]$
 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com