contributed by < m64466805
>
marvin0102
q_free()
的實作中,與其直接刪除 entry
,先使用 list_del()
將 entry
移出串列再進行刪除是比較安全的作法。
q_size()
中,除了判斷 list_empty()
之外,還須判斷 head
是否為 NULL,否則當 head == NULL
時,會變為未定義行為。
你的洞見呢?與其談「心法」,不如設想「如果我是你」,我會怎麼做,示範一次給同學看,而且檢討自己哪裡沒做好,從而呼應原本學員的不足處。
軟體工程師要學會說故事,本作業要求學員從良性詳盡的批評開始。繼續檢討!
jservImage Not Showing Possible ReasonsLearn More →
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
$ gcc --version
gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 46 bits physical, 48 bits virtual
Byte Order: Little Endian
CPU(s): 20
On-line CPU(s) list: 0-19
Vendor ID: GenuineIntel
Model name: 12th Gen Intel(R) Core(TM) i7-12700
CPU family: 6
Model: 151
Thread(s) per core: 2
Core(s) per socket: 12
Socket(s): 1
Stepping: 2
CPU max MHz: 4900.0000
CPU min MHz: 800.0000
BogoMIPS: 4224.00
q_new
commit 17cf102
透過 malloc
配置 list_head
大小的記憶體空間,並使用 list.h
中提供的 INIT_LIST_HEAD
初始化 struct list_head
使用 git rebase -i
重新撰寫 git commit message,務必詳閱作業說明提及的規範
struct list_head *q_new()
{
struct list_head *head = malloc(sizeof(struct list_head));
if (!head) {
return NULL;
}
INIT_LIST_HEAD(head);
return head;
}
commit 17cf102
使用 git rebase -i
重新撰寫 git commit message,務必詳閱作業說明提及的規範
利用 list.h
中提供的 list_for_each_entry_safe
走訪佇列,對每個節點成員作操作,釋放之前配置的記憶體區域。
起初撰寫程式碼時,我對於 entry
和 safe
的資料型別並不清楚,誤以為是 list head
。在重新閱讀你所不知道的 C 語言: linked list 和非連續記憶體中 list
的結構後,我發現要用 element_t
這個型別方能正確運作,因為 element_t
除了包含前後串聯的指標外,還包含了 value
。
void q_free(struct list_head *head)
{
element_t *entry, *safe;
list_for_each_entry_safe (entry, safe, head, list)
q_release_element(entry);
free(head);
}
commit 17cf102
使用 git rebase -i
重新撰寫 git commit message,務必詳閱作業說明提及的規範
使用 qsize
紀錄鏈結串列長度,並利用 list.h
中提供的 list_for_each
中走訪整個鏈結串列,只要經過一個節點,就將qsize
加一,一直執行此操作直到達到串列尾端,並持續記錄節點數量。
int q_size(struct list_head *head)
{
int qsize = 0;
if (list_empty(head)) {
qsize = 0;
}
struct list_head *node;
list_for_each (node, head)
qsize++;
return qsize;
}