首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言單向鏈表常見錯誤:未初始化指標、頭節點處理、記憶體洩漏

     編輯:程式設計綜合問答

原始碼主要問題

  1. 主函數 `La` 未初始化即傳遞: `struct node *La; ... La = InitList(La);` → `InitList` 內參數為傳值,外部 `La` 仍為野指標。
  2. `InitList` 邏輯錯誤: `malloc` 後立即 `L = NULL` 導致記憶體洩漏,且未建立頭節點。
  3. `CreateList` 重複配置頭節點: 每次呼叫都 `malloc` 新頭節點,舊節點洩漏。
  4. `PrintList` 印出頭節點垃圾值: 頭節點不存資料,應從 `head->next` 開始遍歷。
  5. 無記憶體釋放: 程式結束前未 `free` 所有節點。

修正版核心程式碼 (關鍵片段)

// 使用指標的指標 (或引用) 修改呼叫端指標
void InitList(struct node **head) {
    *head = malloc(sizeof(struct node));
    (*head)->next = NULL;
    (*head)->num = 0; // 頭節點不存有效資料
}

void CreateList(struct node **head, int n) {
    struct node *tail = *head;
    for (int i = 0; i < n; i++) {
        struct node *p = malloc(sizeof(struct node));
        scanf("%d", &p->num);
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
}

void PrintList(struct node *head) {
    struct node *cur = head->next; // 跳過頭節點
    while (cur) {
        printf("%d ", cur->num);
        cur = cur->next;
    }
    printf("\n");
}

void FreeList(struct node **head) {
    struct node *cur = *head;
    while (cur) {
        struct node *tmp = cur;
        cur = cur->next;
        free(tmp);
    }
    *head = NULL;
}

int main() {
    struct node *La = NULL; // 初始化為 NULL
    InitList(&La);
    CreateList(&La, 5);
    PrintList(La);
    FreeList(&La);
    return 0;
}

關鍵修正要點

  • **函數修改指標本身需傳 `struct node **` (C) 或 `struct node *&` (C++)**。
  • **頭節點哨兵模式**:頭節點不存資料,`next` 指向第一個資料節點,簡化插入/刪除邏輯。
  • **尾指標 `tail`** 實現 O(1) 尾部插入。
  • **配對 `malloc/free`**,避免洩漏。

完整可執行程式碼已在回答中給出,包含選單迴圈、記憶體釋放、錯誤處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved