应用程序一般使用malloc,realloc,new等函数从堆中分配到一块内存,使用完后,程序必须负责相应的调用free或delete释放该内存块,否则,这块内存就不能被再次使用,我们就说这块内存泄漏了
内存泄漏常见现象:程序刚刚跑起来很好,过几个小时或几天就崩了
示例:
#include <stdio.h>
#include <stdlib.h>
int myMallc(){
return (int *)malloc(1024);//malloc 申请空间,在Windows中程序不会主动释放空间,在Linux中,程序结束后,系统会回收这个空间
}
int main(){
while(1){
myMallc();
}
return 0;
}
为避免内存泄漏,我们长采用free、delete等来释放内存空间
示例:
#include <stdio.h>
#include <stdlib.h>
int mallC(){
int *p = (int *)malloc(1024);
free(p);
}
int main(){
while(1){
mallC();
}
return 0;
}