void *malloc(size_t size);
size 字節內存,成功返回起始地址,失敗返回 NULL。void*,可隱式/顯式轉換為任意指針類型。Type *ptr = (Type *)malloc(sizeof(Type)); // 單個對象 Type *arr = (Type *)malloc(n * sizeof(Type)); // 數組
關鍵三要素:sizeof(Type) 計算大小、強制轉換類型、檢查返回值。
#include <stdio.h>
#include <stdlib.h>
struct Student {
char name[20];
int age;
};
int main() {
// 1. 基本類型
int *pi = (int *)malloc(sizeof(int));
if (!pi) return -1;
*pi = 42;
free(pi);
// 2. 結構體
struct Student *ps = (struct Student *)malloc(sizeof(struct Student));
if (!ps) return -1;
snprintf(ps->name, sizeof(ps->name), "Tom");
ps->age = 20;
free(ps);
// 3. 動態數組(鏈表節點典型用法)
int n = 10;
int *arr = (int *)malloc(n * sizeof(int));
if (!arr) return -1;
for (int i = 0; i < n; ++i) arr[i] = i * i;
free(arr);
return 0;
}
| 特性 | malloc | new |
|---|---|---|
| 返回類型 | void* 需轉換 | 精確類型指針 |
| 大小計算 | 手動 sizeof | 自動 |
| 構造/析構 | 不調用 | 自動調用 |
| 失敗處理 | 返回 NULL | 拋出 bad_alloc |
| 重新分配 | realloc | 無直接對應 |
if (!ptr) { perror("malloc"); exit(1); }free(NULL) 安全無害。NULL:free(p); p = NULL;// 錯誤:未檢查返回值
int *p = (int*)malloc(100 * sizeof(int));
p[50] = 10;
// 正確
int *p = (int*)malloc(100 * sizeof(int));
if (!p) { /* 處理錯誤 */ }
p[50] = 10;
// ...
free(p); p = NULL;
realloc(ptr, new_size):調整已分配塊大小,可能移動內存,返回新地址。aligned_alloc(alignment, size) (C11):分配指定對齊的內存,適用 SIMD、硬件寄存器映射。動態內存管理是 C 語言靈活性的核心,嚴守規範,方能馴服這把雙刃劍。