contributed by <qianzsh>
$ gcc --version
gcc (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0
$ lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
Address sizes: 39 bits physical, 48 bits virtual
CPU(s): 12
On-line CPU(s) list: 0-11
Thread(s) per core: 2
Core(s) per socket: 6
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model:
Model name: Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz
Stepping:
CPU MHz:
CPU max MHz: 4600.0000
CPU min MHz: 800.0000
BogoMIPS: 6399.96
Virtualization:
L1d cache: 192 KiB
L1i cache: 192 KiB
L2 cache: 1.5 MiB
L3 cache: 12 MiB
NUMA node0 CPU(s): 0-11
一開始程式碼為以下
void q_free(struct list_head *head)
{
struct list_head *temp;
while (head) {
temp = head->next;
free(head);
head = temp;
}
}
後來發現自己對佇列的理解有誤。起初,以為每個節點都是 list_head 結構體,但實際上只有佇列的頭部是 list_head,其餘節點均為 element_t 結構體,因此,在釋放記憶體時,不僅要釋放佇列頭部,還必須釋放各節點內部指標所指向的記憶體。
void q_free(struct list_head *head)
{
if (!head)
return;
struct list_head *current = head->next, *next;
while (current != head) {
next = current->next;
element_t *entry = list_entry(current, element_t, list);
free(entry->value);
free(entry);
current = next;
}
free(head);
}
作業