動態分配出來空間在堆裏,如果動態分配出來的空間使用完成後不回收,只會在所屬的進程退出,系統纔會回收。如果進程一直不退,動態分配越來越多的空間,會引起系統可用內存不足,這就是內存泄漏。
注意:分配在堆裏的空間,所在函數執行結束也不會自動回收分配在堆裏的空間(會自動回收棧裏分配的空間).只有調用回收函數或者進程退出纔可以回收堆裏分配的空間。
檢查C/c++程序執行時是否有內存泄漏,可用命令:<valgrind 可執行文件>
1
2 #include<iostream>
3 #include<stdlib.h>
4
5 int main(void)
6 {
7 int *p;
8
9 p = (int*)malloc(sizeof(int)); // 只有動態分配,沒有回收
10 return 0;
11 }
編譯後,用命令檢查:
[root@localhost05new_delete]# valgrind ./a.out
==7001== Memcheck, amemory error detector
==7001== Copyright(C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==7001== UsingValgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==7001== Command:./a.out
==7001==
==7001==
==7001== HEAPSUMMARY:
==7001== in useat exit: 4 bytes in 1 blocks
==7001== totalheap usage: 1 allocs, 0 frees, 4 bytes allocated
==7001==
==7001== LEAKSUMMARY:
==7001== definitely lost: 4 bytes in 1 blocks
==7001== indirectly lost: 0 bytes in 0 blocks
==7001== possibly lost: 0 bytes in 0 blocks
==7001== stillreachable: 0 bytes in 0 blocks
==7001== suppressed: 0 bytes in 0 blocks
==7001== Rerun with--leak-check=full to see details of leaked memory
==7001==
==7001== For countsof detected and suppressed errors, rerun with: -v
==7001== ERRORSUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)
在代碼里加上回收空間的處理
1
2 #include<iostream>
3 #include<stdlib.h>
4
5 int main(void)
6 {
7 int *p;
8
9 p = (int*)malloc(sizeof(int));
10
11 free(p);
12 return 0;
13 }
再編譯,檢查:
[root@localhost05new_delete]# valgrind ./a.out
==7519== Memcheck, amemory error detector
==7519== Copyright(C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==7519== UsingValgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==7519== Command:./a.out
==7519==
==7519==
==7519== HEAPSUMMARY:
==7519== in useat exit: 0 bytes in 0 blocks
==7519== totalheap usage: 1 allocs, 1 frees, 4 bytes allocated
==7519==
==7519== All heapblocks were freed -- no leaks are possible
==7519==
==7519== For countsof detected and suppressed errors, rerun with: -v
==7519== ERRORSUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)
在C語言裏用malloc函數動態分配空間,用free函數回收空間。
在C++語言裏用new關鍵字動態分配空間,用delete關鍵字回收空間.
C++:
int *p, *p2 ;
//動態分配一個int型的變量空間
p = new int; // new 後面直接寫類型
//動態分配一個int型的數組空間,數組元素個數爲5
p2 = new int [5];
//回收空間
delete p;
delete [] p2; //回收連續的空間時,<delete>後需加上”[]”符號
注意:在c++裏也是可以c裏的malloc分配空間,free回收空間.但是建議還是改成使用C++的new與delete,因爲它們有比malloc/free更多的功能.
new 會觸發類的構造函數,delete會觸發類的析構函數.而malloc/free是無法觸發這些函數的.
c++裏通常會用到一個詞“對象”
對象其實就是分配出來的某種類型的具體空間.
如有類型,MyCls;
MyCls a; //a 就是對象
MyCls *a = newMyCls; // a指向對象.“new MyCls”創建出對象,並把地址給指針變量a存放起來.
建議儘量使用後面這種方法創建對象,這樣比較安全.
本文由廣州尚觀科技發佈,廣州尚觀科技,專業的嵌入式/Linux/Java大數據/python/UI培訓機構。掃下方二維碼關注我們,可獲得免費精品視頻一份。