问题:如何在不使用“free()”函数的情况下动态解除分配内存。
解决方案:标准库函数realloc()可用于释放先前分配的内存。下面是“stdlib.h”中“realloc()”的函数声明
如果“size”为零,则调用 realloc 等价于“free(ptr)”。如果“ptr”为 NULL 且 size 不为零,则调用 realloc 等价于“malloc(size)”。
让我们用简单的例子来检查一下。
使用 valgrind 工具检查泄漏摘要。它显示 10 字节的内存泄漏,以红色突出显示。
检查 valgrind 的输出。它显示没有内存泄漏是可能的,以红色突出显示。
void *realloc(void *ptr, size_t size);
/* code with memory leak */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *ptr = (int*)malloc(10);
return 0;
}
[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;
}
[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]$