[英]What happens to malloc'ed memory after exec() changes the program image?
[英]When a program terminates what happens to the memory allocated using malloc that is not free'ed?
說我有以下程序
#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,solarix,macos等。這個代碼在終止期間的行為有什么不同嗎?
其他答案告訴你兩個重要的事情:
free()
它。 但是,重要的是要說明為什么 free()
所有你已經編寫過的東西都是好的做法。 在我看來:
操作系統將回收未釋放的內存。
但釋放malloc
分配的所有內存是一種很好的做法
程序退出后,操作系統將回收內存。
操作系統不了解您的程序泄漏內存,它只是將內存分配給程序進行運行,一旦程序退出就回收內存。
但是,操作系統可能會/可能不會重新調整文件描述符等其他資源,從而導致資源泄漏。
因此,一個好的做法是程序應該在退出之前清理它所使用的所有資源。
當進程動態分配內存時,它會從OS借用內存塊。 當一個進程不需要分配內存時,它就會釋放。 然后OS將這些塊添加到其空閑列表中。 當進程終止時也會發生同樣的情況。 操作系統回收該過程使用的所有塊。
更重要的是,FREE確保您分配的內存/緩沖區的健全性,從而存在一個良好的檢查點來抑制/追趕堆損壞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.