San*_*raj 16 c malloc free valgrind memory-leaks
说我有以下程序
#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;
}
Run Code Online (Sandbox Code Playgroud)
上面的程序调用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)
Run Code Online (Sandbox Code Playgroud)
题:
当程序终止时,分配的内存会发生什么但不是free
'd?
更新:考虑这个代码是在不同的操作系统上执行的 - 比如windows,linux,solarix,macos等.这个代码在终止期间的行为有什么不同吗?
Tim*_*nes 14
其他答案告诉你两个重要的事情:
free()
它.但是,重要的是要说明为什么对free()
你所做的每一件事都是好的做法.在我看来: