// 隊列銷毀:遍歷鏈表節點逐個 free
void DestroyQueue(LinkQueue *q) {
while (q->front) {
q->rear = q->front->next;
free(q->front);
q->front = q->rear;
}
}
// 鏈表銷毀:僅 free 頭指針(錯誤示範)
void DestroyLinkList(LinkList *L) {
free(L); // 僅釋放頭結點,其餘節點洩漏!
}
隊列與鏈表是邏輯結構,銷毀方式取決於物理存儲實現:
free(q->base) 釋放數組DestroyLinkList 代碼嚴重錯誤(僅釋放頭結點)void DestroyLinkList(LinkList *L) {
Node *p = L->next; // 假設帶頭結點
while (p) {
Node *tmp = p;
p = p->next;
free(tmp);
}
free(L); // 最後釋放頭結點
*L = NULL; // 避免野指針
}
malloc 對應一個 freeNULL 防野指針數據結構銷毀無標準答案,只有「與分配方式匹配」的正確實現。理解底層存儲(順序/鏈式)是編寫正確銷毀函數的前提。