[英]Segmentation fault in Linked list /C
我想從我的鏈表中刪除最后一項,但是變成了分段錯誤。 所以一些指針是錯誤的。 這是我的代碼。
#include <stdio.h>
#include <stdlib.h>
struct listenElement{
int wert;
struct listenElement *next;
};
static struct listenElement* anfang = NULL;
int removeElement(void) {
if (anfang == NULL){
return -1;
}
else{
int l = NULL;
struct listenElement *p = anfang->next ;
if (p->next == NULL){
l = p->wert;
free(p);
anfang->next = NULL;
}
else
{
while(p->next != NULL){
anfang = p;
p = p->next;
l = p->wert;
free(p);
}
anfang =p;
anfang->next= NULL;
}
return l;
}
}
注意一旦你在某個指針上調用free就無法訪問該指針(內存也通過其他指針),這樣做會調用未定義的行為 - 這是一個非法的內存指令,可以在運行時檢測到可能導致 - 分段錯誤好:
以下代碼錯誤:
while(p->next!=NULL){// <--+ you use `p` - that is invalid
anfang = p; // |
p = p->next; // |
l = p->wert; // |
free(p);//-------------+ you free `p`
}
另外學習縮進C程序 。
你的代碼中還有一些錯誤:
邏輯不正確,當只有一個節點存在時,您不會考慮這種情況。 你需要添加,
// this first pice of code to add // Case-1: when nodes in linked list are = 1 if (anfang->next == NULL){ free(anfang); anfang = NULL; reset to NULL return 1; // as you returns }
你可以改進循環,並且在循環和循環之后使用anfang
是錯誤的。 anfang
應該總是指向第一個節點,你只需要刪除最后一個節點。 如果鏈表中有多個節點,那么anfang
值不會改變(讀取注釋):
// this code should be after above code // Case-2: when nodes in linked list are > 1 p = anfang; // last = anfang->next; // last node // a loop for travel to reach - last node in linked list while(last->next != NULL){//stop when last - points to last node p = last; // every time before update last make `p` the `last` last = last->next; } p->next = NULL; // make `p` as last node, to remove last node free(last); // free memory for last node
從邏輯上講,你錯了,在你的代碼中你可以在while循環中自由調用,而你的目標是只刪除一個 - 最后一個節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.