鏈表是 C 語言學習者接觸動態記憶體管理的經典案例,但 malloc 失敗、野指標、記憶體洩漏等問題層出不窮。本文針對常見錯誤提供診斷思路與修正範例。
struct Node {
int data;
struct Node *next;
};
// 錯誤示範
struct Node *head = malloc(sizeof(struct Node));
head->data = 10; // 未檢查 malloc 回傳值
head->next = NULL; // 未初始化 next 指標
while (head->next) { ... } // 可能因未初始化導致死循環或段錯誤
next 指向隨機位址,遍歷時觸發未定義行為struct Node *create_node(int val) {
struct Node *p = malloc(sizeof(struct Node));
if (!p) {
perror("malloc failed");
return NULL;
}
p->data = val;
p->next = NULL; // 關鍵:初始化指標
return p;
}
// 建立鏈表:以輸入 -1 為結束條件
struct Node *build_list() {
int val;
struct Node *head = NULL, *tail = NULL;
while (scanf("%d", &val) == 1 && val != -1) {
struct Node *node = create_node(val);
if (!node) break; // 分配失敗提前退出
if (!head) head = tail = node;
else {
tail->next = node;
tail = node;
}
}
return head;
}
對於生產環境,建議封裝「安全分配器」統一處理錯誤、記錄日誌;大型專案可引入記憶體池減少碎片。學習階段務必養成「分配-檢查-初始化-使用-釋放」的完整習慣。