1. 程式人生 > >malloc/free 與 new/delete

malloc/free 與 new/delete

相同點:

  • 都可用於申請動態記憶體和釋放記憶體

不同點:

  1. malloc 和 free 是C/C++ 標準庫函式, new / delete 是 C++ 的運算子
  2. new 自動計算需要分配的空間,而 malloc 需要手工計算所需位元組數
  3. new 是型別安全的,而 malloc 不是;例:
int *p = new float[2]; //編譯時指出錯誤
int *p = (int*) malloc(2*sizeof(double));//編譯時無法指出錯誤
  1. new 呼叫 operator 分配足夠的空間,並呼叫相關物件的建構函式,而 malloc 不能呼叫建構函式;delete 將呼叫該例項的解構函式,然後呼叫類的 operator delete ,以釋放該例項佔用的空間,而free 不能呼叫解構函式
  2. malloc/free 需要庫檔案支援, new/delete 則不需要