原代碼有幾個問題:
1)while(next != NULL)
循環試圖使用已釋放的節點。
2)該循環已經照顧了釋放root
(next = root;
),所以不需要單獨發佈root
。
3)爲使while
環路正常工作,列表中的tail
/head
必須正確地以NULL
終止。 (我在第一個for
循環中添加了終止)
4)第二個循環應該打印所有的x
值。它沒。櫃檯只有一個號碼。
該程序的改進變體如下。請檢查程序輸出。
#include <stdio.h>
#include <stdlib.h>
struct node{
int x;
struct node *next;
};
int main(void){
struct node *root, *next, *to_free;
root = malloc(sizeof(struct node)); // 1 malloc
root->x = 777;
root->next = NULL;
printf("allocating memory for root. root->x = %i\n\n", root-> x);
next = root; // next points to "head" (root)
for (int i = 0; i <= 10; i++){
next->next = malloc(sizeof(struct node)); // 11 mallocs
printf("allocating memory for next. next->x = %i\n", i+1);
next->next->x = i+1; //
next = next->next;
next->next = NULL; // list termination is needed!
}
printf("\n");
next = root; // next points to "head" (root)
for (int j = 0; j <= 11; j ++){ // 12 nodes has to be printed!
printf("Printing x = %i\n", next->x);
next = next->next;
}
printf("\n");
next = root; // next points to "head" (root)
while(next != NULL)
{
to_free = next; // we will free `next` as `to_free` soon
next = next->next; // move to the next node
printf("deallocating node with x = %i\n", to_free->x);
free(to_free); // now free the remembered `next`
}
return 0;
}
輸出:
allocating memory for root. root->x = 777
allocating memory for next. next->x = 1
allocating memory for next. next->x = 2
allocating memory for next. next->x = 3
allocating memory for next. next->x = 4
allocating memory for next. next->x = 5
allocating memory for next. next->x = 6
allocating memory for next. next->x = 7
allocating memory for next. next->x = 8
allocating memory for next. next->x = 9
allocating memory for next. next->x = 10
allocating memory for next. next->x = 11
Printing x = 777
Printing x = 1
Printing x = 2
Printing x = 3
Printing x = 4
Printing x = 5
Printing x = 6
Printing x = 7
Printing x = 8
Printing x = 9
Printing x = 10
Printing x = 11
deallocating node with x = 777
deallocating node with x = 1
deallocating node with x = 2
deallocating node with x = 3
deallocating node with x = 4
deallocating node with x = 5
deallocating node with x = 6
deallocating node with x = 7
deallocating node with x = 8
deallocating node with x = 9
deallocating node with x = 10
deallocating node with x = 11
來源
2018-02-14 16:34:11
sg7
我做循環的第一線釋放是相同的循環的最後一行,仍然收到了同樣的錯誤。你能幫忙嗎? – DMop
沒有看到你是如何改變代碼的,也不知道哪個'free'有問題,不是真的。 –