[英]Why don't we use free(node) when inserting in a linked list?
void push(struct node **head, int data)
{
struct node* newnode = malloc(sizeof(struct node));
newnode->data = data;
newnode->next = *head;
*head=newnode;
}
I came across this function, I wonder why didn't we use free(newnode) since we affected its value to *head and we no longer have use of it?我遇到了这个 function,我想知道为什么我们不使用 free(newnode) ,因为我们影响了它对 *head 的值并且我们不再使用它?
If you will free the node pointed to by the pointer newnode
then as a result the pointer *head
due to this statement如果您将释放指针
newnode
指向的节点,则结果指针*head
由于此语句
*head=newnode;
will point to a deleted node.将指向已删除的节点。 As a result the pointer
*head
will be invalid.结果,指针
*head
将无效。
That is after this statement那是在这个声明之后
*head=newnode;
the both pointers *head
and newnode
point to the same one node.两个指针
*head
和newnode
都指向同一个节点。 If you will write如果你会写
free( newnode );
or或者
free( *head );
the pointed node will be deleted.指向的节点将被删除。 So you nothing added to the list.
所以你什么都没有添加到列表中。 What you was going to add to the list you deleted.:) And moreover you substituted a correct value in the pointer
*head
(before calling the function) for an invalid value (address) that points nowhere after deleting the node.您将要添加到您删除的列表中的内容。:) 此外,您将指针
*head
中的正确值(在调用函数之前)替换为在删除节点后无处指向的无效值(地址)。
Pay attention to that it would be more correct to define the function the following way请注意,使用以下方式定义 function 会更正确
int push( struct node **head, int data )
{
struct node *newnode = malloc( sizeof( struct node ) );
int success = newnode != NULL;
if ( success )
{
newnode->data = data;
newnode->next = *head;
*head = newnode;
}
return success;
}
In that case the function will not have undefined behavior when there is no enough memory to allocate a new node.在这种情况下,当没有足够的 memory 来分配新节点时,function 将不会有未定义的行为。 And the user of the function can check whether adding a new node was successful.
function的用户可以查看添加新节点是否成功。
You mustn't do free(newnode);
你不能做
free(newnode);
here because the new node is added to the list and therefore will be used later.这里是因为新节点已添加到列表中,因此稍后将使用。
Also the variable newnode
itself is (typically) allocated on the stack and will be freed automatically when exiting from the function, so you don't need to manyally free that.此外,变量
newnode
本身(通常)是在堆栈上分配的,并且在从 function 退出时会自动释放,因此您不需要大量释放它。
Because *head will refer the dead newnode
.因为 *head 将引用死的
newnode
。 You have to free them in the end of the code.您必须在代码末尾释放它们。 Actually, you don't need to get
head
as double pointer.实际上,您不需要将
head
作为双指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.