簡體   English   中英

分段故障鏈表

[英]segmentation fault linked list

我看到一些類似的話題,但是他們沒有幫助我。 我有一個鏈表,和一個插入元素的函數。

struct node{
    int data;
    struct node* next;
} node;

struct node* head;

void insert(struct node* head,int x);
int main(){
    struct node* head = (struct node*) malloc(sizeof(struct node));
    int x;
    while(1){
        printf("Please enter number\n");
        scanf("%i", &x);
        insert(head,x);
        print(head); // function that works
    }
    return 0;
}
void insert(struct node* head,int x){
    struct node* temp = malloc(sizeof(struct node));
    temp->data = x;
    temp->next = NULL;
    if(head->next != NULL) temp->next = head;
    head = temp;
    free(temp);
}

GDB說我在if構造的線上遇到分段錯誤:

if(head->next != NULL) temp->next = head;

我的錯誤在哪里?

你需要檢查head調用之前if(head->next != NULL) temp->next = head; head可能包含NULL。 因此在if(head->next != NULL) temp->next = head;之前添加if(head != NULL) if(head->next != NULL) temp->next = head;

編輯:如果您在提問時張貼完整代碼,則很容易以適當的方式為您提供幫助。 現在人們以為我們回答錯了,他們投反對票了。 好的,這是我的答案。 您不應該撥打free(temp); 在插入功能本身。 因為您將要在print功能中訪問該內存。 您正在釋放自己在insert()分配的內存,並嘗試在print函數中進行訪問。 這導致了分段錯誤。 刪除free(temp); 從插入功能。

是的,這當然會導致分割錯誤。 if條件下,您正在訪問head->next head只是struct node類型的指針。 首先分配內存空間,然后訪問該字段。 現在,您正在訪問(head->next) ,這是內存中的一些不合適的地址,內核會給進程帶來“分段錯誤”。 例如,是否struct node* head = malloc(sizeof(struct node)); 然后可以訪問head->next

請注意,您要聲明兩個具有相同名稱(頭)但作用域不同的變量:

struct node* head;

void insert(struct node* head,int x);
int main()
{
  struct node* head = (struct node*) malloc(sizeof(struct node));

在插入函數中,在檢查“ head”是否為NULL之前先取消引用“ head”。 始終檢查是否為空,切勿承擔任何責任。 在函數的最后,您釋放了新創建的節點 ,這也是錯誤的。 最后,insert函數的參數不正確,您需要傳遞指針的地址才能更改head指向的內容。

該函數應該看起來像這樣

void insert(struct node** head,int x)
{
  struct node* temp = malloc(sizeof(struct node));
  temp->data = x;
  temp->next = NULL;

  assert( head != NULL ); // should always be an address

  if ( *head == NULL ) 
  {
    *head = temp; // done, first in list
  }
  else // insert as first in list
  {
    tmp->next = *head; 
    *head = tmp;       
  }
}

您應該這樣稱呼它:

insert(&head,x);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM