void* malloc(size_t size);
核心:**型別轉換** + **sizeof 計算**。
malloc 回傳 void*,**必須顯式轉型**:
int* p = (int*)malloc(sizeof(int) * length);
16/32 位元環境 int 大小不同,float 同為 4 bytes。良好習慣:
cout << sizeof(char) << endl;
cout << sizeof(int) << endl;
cout << sizeof(unsigned int) << endl;
cout << sizeof(long) << endl;
cout << sizeof(unsigned long) << endl;
cout << sizeof(float) << endl;
cout << sizeof(double) << endl;
cout << sizeof(void*) << endl;
**陷阱**:p = malloc(sizeof(p)) —— sizeof(p) 是指標大小 (4/8 bytes),非目標型別大小!
void free(void* memblock);
指標型別與指向記憶體大小**編譯期已知**,free(p) 即可精準釋放。
free(nullptr) 多次調用安全;free(非空指標) 連續兩次 → **執行期錯誤** (雙重釋放)。