假设我有以下程序
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int * i;
if ((i = malloc(sizeof(int) * 100)) == NULL) {
printf("EROOR: unable to allocate memory \n");
return -1;
}
/* memory is allocated successfully */
/* memory is not free'ed but program terminates */
// free(i);
return 0;
}
以上程序调用malloc
来分配一些内存,但没有调用free
来释放它。程序在未释放内存的情况下终止。
Valgrind 明显检测到了内存泄漏。
<snap>
==14209== HEAP SUMMARY:
==14209== in use at exit: 400 bytes in 1 blocks
==14209== total heap usage: 1 allocs, 0 frees, 400 bytes allocated
==14209==
<sanp>
==14209== LEAK SUMMARY:
==14209== definitely lost: 400 bytes in 1 blocks
==14209== indirectly lost: 0 bytes in 0 blocks
==14209== possibly lost: 0 bytes in 0 blocks
==14209== still reachable: 0 bytes in 0 blocks
==14209== suppressed: 0 bytes in 0 blocks
==14209==
==14209== For counts of detected and suppressed errors, rerun with: -v
==14209== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
问题:
程序终止时,分配但未被free
的内存会发生什么?
更新: 考虑此代码在不同的操作系统上执行-比如Windows,Linux,Solaris,macOS等。在终止时,此代码的行为是否有所不同?
free
函数的。通常情况下,我们需要处理非常庞大的代码库,其中malloc
函数由一个模块完成,而free
函数则由另一个模块完成等等。这些程序可以在 Windows、Solaris、Linux 和 Mac OS 等多种操作系统上运行。因此,我很好奇未释放内存的情况是如何处理的。 - Sangeeth Saravanaraj