代碼審視
struct student *del(struct student *head, int num) {
struct student *p1, *p2 = NULL;
if (head = NULL) { // 錯誤:賦值而非比較
printf("空鏈表");
} else {
p1 = head;
while ((num != p1->num) && (p1->next != NULL)) {
p2 = p1;
p1 = p1->next;
}
if (num == p1->num) { ... }
}
return head;
}
致命錯誤
if (head = NULL) 應為 if (head == NULL),導致頭指針被置空,隨後訪問 p1->num 觸發段錯誤。
- 未處理
head 為空時的返回值,調用者 p = del(head, num); 可能收到野指針。
scanf("%d %f", ...) 讀取浮點數但結構體 score 為 float,格式匹配,但輸入非數字會導致死循環。
調試方法
- VS:
F9 斷點,F5 運行,崩潰時查看 Call Stack (Alt+7) 定位崩潰行。
- 打印關鍵指針地址:
printf("head=%p p1=%p\n", head, p1);。
- 使用
valgrind (Linux) 或 AddressSanitizer (GCC/Clang -fsanitize=address) 檢測內存越界/使用後釋放。
修正要點
struct student *del(struct student *head, int num) {
if (head == NULL) return NULL; // 修正比較
struct student *p1 = head, *p2 = NULL;
while (p1 != NULL && num != p1->num) {
p2 = p1;
p1 = p1->next;
}
if (p1 == NULL) { // 未找到
printf("無此數據\n");
return head;
}
if (p1 == head) head = head->next;
else p2->next = p1->next;
free(p1);
printf("已刪除\n");
return head;
}