问题:如何在不使用“ 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
#include
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
#include
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]$
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。