簡體   English   中英

在我的單鏈列表實現中,即使我為要釋放的節點分配了內存,但指向該節點的指針不是NULL,為什么仍然如此?

[英]In my Singly linked List implementation why is it even though I allocated memory for the node to be freed, the pointer to the Node isn't NULL?

使用delete_SLL函數,我要刪除此單鏈接列表的標題(head = 4)。 盡管我得到了正確的輸出,但是保存head值的var struct Node *“ temp”不是NULL。 自由函數不喜歡的變量“ temp”是什么? 將節點temp設置為等於列表頭時是否未對節點temp進行Malloc?

來源:刪除節點

碼:

#include <stdio.h>
#include <stdlib.h>
struct Node{
  int item;
  struct Node* next;
};

struct List{
  struct Node* head;
  struct Node* tail;
};

int SLL_empty(struct List* lst){
  return lst->head == NULL ;
}

//newLst work
struct List newLst(){
  struct List  lst;
  lst.head = NULL;
  lst.tail = NULL;
  return lst;
}


//Inserts a node to the front of the list[WORKS]
void insert_SLL(struct List* lst, int x){
  struct Node* nde = (struct Node*)malloc(sizeof(struct Node));
  nde->next = lst->head;
  nde->item = x;
  if (SLL_empty(lst))
    lst->tail=nde;
  lst->head = nde;
}


//Deletes a given Node
void delete_SLL(struct List* lst, int x){
  struct Node* temp =  (struct Node*)malloc(sizeof(struct Node));;
  temp = lst->head;
  struct Node* prev = NULL;`enter code here`

  //If the head has the key
  if (temp != NULL && temp->item == x){
    lst->head = temp->next;
    temp->next = NULL;
    free(temp);
  }

  // stops once the key is found
  while(temp != NULL && temp->item != x){
    prev = temp;
    temp= temp->next;
  }

  //If not in list
  if (temp == NULL) return;

  //If middle
  if (temp != NULL && temp->item == x){
    prev->next = temp->next;
    temp->next = NULL;
  }

  //if at the end
  if (temp != NULL && temp->item == lst->tail->item){
    lst->tail= prev;
    prev->next = NULL;
  }
  free(temp);
}

int SLL_pop(struct List *list){
 struct Node* nde = list->head;
 int item = nde->item;
  list->head = nde->next;
  free(nde);
  if (SLL_empty(list))
    list->tail = NULL;
  return item;
}

int main(int argc, const char * argv[]) {
  int i;
  struct List list = newLst();
  for (i = 0; i < 5; ++i)
   insert_SLL(&list, i);
//  printf("The length of the linkedLst is: %d\n",SLL_length(&list));

  delete_SLL(&list, 4);
  while ( list.head != NULL )
    printf("Node: %d\n", SLL_pop(&list));

  return 0;
}

free()的主要目的是要求操作系統將分配的內存帶回系統。 您可能無法“看到”該消息,但是如果以后嘗試在“臨時”訪問任何元素,則應該會收到錯誤消息。

而程序中的“臨時”只是一個變量。 由於傳遞值的意義,C不需要,也不能將給定的指針更改為NULL。 記住該指針不再有效是程序員的工作。
或者,您可以在每次釋放指針時將其手動設置為NULL。

暫無
暫無

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

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