首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

高品質 C++/C 程式設計指南:malloc/free 使用要點與 sizeof 陷阱

     編輯:VC 教學

malloc 原型與正確用法


void* malloc(size_t size);
// 申請 length 個 int
int* p = (int*)malloc(sizeof(int) * length);

兩大關鍵要素

  1. 型別轉換:malloc 回傳 void*,C++ 必須顯式轉換為目標指標型別。
  2. sizeof 運算子:malloc 僅關心位元組數,不識別型別。務必使用 sizeof(型別) * 個數,避免硬編碼位元組數(16/32 位元平台 int 大小不同)。

驗證平台型別大小


cout << sizeof(char) << endl;        // 1
cout << sizeof(int) << endl;         // 2 或 4
cout << sizeof(unsigned int) << endl;
cout << sizeof(long) << endl;
cout << sizeof(unsigned long) << endl;
cout << sizeof(float) << endl;       // 4
cout << sizeof(double) << endl;      // 8
cout << sizeof(void*) << endl;       // 4 或 8

常見錯誤:sizeof(p) 而非 sizeof(*p)


// 錯誤:p 是指標,sizeof(p) 為指標大小(4/8),非 int 大小
int* p = (int*)malloc(sizeof(p)); 

// 正確
int* p = (int*)malloc(sizeof(*p) * length); // 或 sizeof(int) * length

free 使用要點


void free(void* memblock);
  • free(p) 正確釋放,因指標型別與配置大小編譯期已知。
  • p == NULL 多次 free 安全無害。
  • p != NULL 連續 free 兩次導致未定義行為(通常崩潰)。

最佳實務

  • C++ 新代碼優先使用 new/delete 或智慧指標/容器。
  • 必須用 malloc/free 時(對接 C 庫、共享記憶體),嚴守型別轉換與 sizeof 規則。
  • 配配對:malloc 配 free,new 配 delete,new[] 配 delete[],絕不混用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved