代碼實現單鏈表建立與遍歷,運行到末尾出現錯誤,典型指針問題。
struct student *cin(void) {
struct student *head, *p1, *p2;
head = p2 = p1 = (struct student*)malloc(N);
scanf("%d", &(*p2).num);
while ((*p2).num != 0) {
p1 = (struct student*)malloc(N);
scanf("%d", &p1->num);
if (p1->num == 0) break;
(*p2).next = p1;
p2 = p1;
}
p1 = NULL; // 問題1:p1 指向 NULL
(*p2).next = 0; // 問題2:p2 可能是最後一個有效節點,next 設為 0 正確
return head; // 但 head 指向第一個節點,若第一個輸入即為 0 則 head 為垃圾值
}
head 指向已分配但未初始化的節點,且 num=0 導致列表為空但 head 非 NULLp1 先分配再讀取,導致最後多分配一個節點struct student *createList() {
struct student *head = NULL, *tail = NULL, *newNode;
int num;
while (1) {
scanf("%d", &num);
if (num == 0) break;
newNode = (struct student*)malloc(sizeof(struct student));
newNode->num = num;
newNode->next = NULL;
if (head == NULL) head = tail = newNode;
else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
valgrind 或 VS 除錯器檢測記憶體錯誤malloc 後檢查返回值是否為 NULLvoid printList(struct student *head) {
while (head != NULL) {
printf("%d\n", head->num);
head = head->next;
}
}