一、new和malloc的基本概念
new和malloc都是用於動態分配內存的函數。dynamic memory allocation是指在程序運行時動態分配內存,也稱堆分配(heap allocation),與靜態內存分配(即編譯時內存分配)相對應。C++引入了new和delete來代替C語言中常用的malloc和free。
malloc(memory allocation)函數定義在stdlib.h頭文件中。malloc函數申請一塊指定大小的內存塊,並返回指向該內存塊的指針。內存中的數據是未初始化的,需要使用memset函數來清零。
new和delete是C++的關鍵字,是一對運算符。使用new運算符可以動態分配內存,並返回指向新內存的指針,而使用delete則可以將內存釋放。
//malloc的用法示例 #include int main(){ int *p = (int*)malloc(sizeof(int)); *p = 10; free(p); return 0; } //new的用法示例 #include int main(){ int *p = new int; *p = 10; delete p; return 0; }
二、new與malloc的區別
1.返回值類型不同
malloc返回void類型指針,在C++語言中需要進行強制類型轉換才能賦值給指定類型的指針。new則返回指定類型的指針,不需要進行強制類型轉換。
#include #include int main(){ int *p = (int*)malloc(sizeof(int)); int *q = new int; std::cout << typeid(p).name() << std::endl; std::cout << typeid(q).name() << std::endl; free(p); delete q; return 0; } //運行結果:Pv(void指針類型), Pi(int指針類型)
2.運算符重載
new和delete是C++的關鍵字,是一對運算符,支持重載。使用new可以自動調用構造函數,使用delete可以自動調用析構函數。
#include class A{ public: A(){std::cout << "A constructor" << std::endl;} ~A(){std::cout << "A destructor" << std::endl;} }; int main(){ A *a1 = (A*)malloc(sizeof(A)); A *a2 = new A(); free(a1); delete a2; return 0; } //運行結果只有new能調用構造函數和析構函數
3.內存越界檢查
new進行內存分配時,會進行越界檢查。
#include #define LEN 10 int main(){ int *p1 = (int*)malloc(sizeof(int) * LEN); int *p2 = new int[LEN]; for(int i = 0; i < LEN+5; ++i){ std::cout << p1[i] << " "; //越界訪問p1,並不會拋出異常 } std::cout << std::endl; for(int i = 0; i < LEN+5; ++i){ std::cout << p1[i] << " "; //越界訪問p2,會拋出異常 } free(p1); delete[] p2; return 0; }
4.分配對象空間不同
new可以同時分配對象和空間,而malloc只能分配空間。
#include #include class A{ public: int x; char* str; }; int main(){ A *a1 = (A*)malloc(sizeof(A)); //只分配空間,需要手動初始化對象 a1->x = 1; a1->str = (char*)malloc(sizeof(char) * 10); strcpy(a1->str, "hello"); std::cout << "x = " <x << ", str = " <str <str); free(a1); A *a2 = new A(); //分配空間並初始化對象 a2->x = 2; a2->str = (char*)malloc(sizeof(char) * 10); strcpy(a2->str, "world"); std::cout << "x = " <x << ", str = " <str <str); delete a2; return 0; }
三、小結
new和malloc都是用於動態分配內存的函數。new和delete是C++的關鍵字,支持運算符重載和對析構函數的調用,可以自動調用構造函數和析構函數。new進行內存分配時會進行內存越界檢查,malloc不會。new可以同時分配對象和空間,而malloc只能分配空間。選擇使用哪個函數,需要結合具體的情況來考慮。
原創文章,作者:KJHQB,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/332953.html