【发布时间】:2021-02-18 01:27:08
【问题描述】:
在this TED talk 中,Torvalds 提出了一个不带 if 条件的删除入口函数。我尝试在下面的代码中进行模拟,但如果要删除的条目是列表的头部,则它不起作用。 1.)为什么这不能专门去除头部? 2.) 由于我们从不释放条目,这种方法不会产生内存泄漏吗?
/** a data structure representing a node **/
struct node {
int data;
struct node* next;
};
/** create a new node and return a pointer to it**/
struct node* new_Node(int data)
{
struct node* newP = malloc(sizeof(struct node));
newP-> data = data;
newP-> next = NULL;
return newP;
}
/** function to print out a list**/
void list_print(struct node* head)
{
printf("Begin List Print:\n");
struct node* tmp = malloc(sizeof(struct node));
tmp = head;
while(tmp != NULL ) {
printf("%d\n", tmp->data);
tmp = tmp->next;
}
printf("End List Print\n\n");
}
/** function to delete one node **/
void list_remove_entry(struct node* head, struct node* entry)
{
struct node** indirect = &head;
while((*indirect) != entry) {
indirect = &(*indirect)->next;
}
*indirect = (*indirect)->next;
}
/** the program entry point**/
int main()
{
struct node* head = new_Node(1);
struct node* n1 = new_Node(2);
struct node* n2 = new_Node(3);
head->next = n1;
n1->next = n2;
list_print(head);
list_remove_entry(head, head);
list_print(head);
return 0;
}
【问题讨论】:
-
Torvalds 方法依赖于使用
node**参数。 -
是的,如果您从不释放该条目,您就会发生内存泄漏。他可能会假设一种垃圾收集语言。
标签: c pointers singly-linked-list