[英]possible memory leak using pointers with malloc() and free(), and confusion with pointer notation
So I'm relatively new to C, and I was trying to write code for a singly linked list. 因此,我对C还是比较陌生,我正尝试为单链表编写代码。
This is what I wrote for deleting a node from the beginning of the list. 这就是我为从列表开头删除节点而写的内容。
int delete(struct node **head)
{
int x = -1;
if(*head != NULL) {
struct node *old = *head;
(*head) = (*head)->next;
x = old->data;
free(old);
}
return x;
}
and I'm confused at the free()
function. 我对
free()
函数感到困惑。 Am I freeing the space allocated to the pointer old
, or am I freeing it to the address at which old
points? 我是将分配给指针的空间释放为
old
还是将其释放为old
点的地址? Maybe the correct way of doing it would be free(*old)
? 也许正确的做法是
free(*old)
? Will this code cause a memory leak? 此代码会导致内存泄漏吗?
Also, if this frees the memory allocated to old, what would be the effect of free(&old)
, in that case? 另外,如果这释放了分配给old的内存,那么
free(&old)
的结果将是什么?
From what you show the memory management seems OK and does not seem to leak memory. 从您显示的内容来看,内存管理似乎还可以,并且似乎不会泄漏内存。
Am I freeing the space allocated to the pointer old
我要释放分配给指针的空间吗?
Yes, the code deallocates, frees to memory old
points to, which is commonly referred to as the memory being allocated to a pointer . 是的,代码将释放
old
点,将old
点释放到内存中,这通常称为将内存分配给指针 。
free(*old)
wouldn't work, as it wouldn't compile, because you tried to pass a struct
into where a pointer is expected. free(*old)
不起作用,因为它无法编译,因为您试图将struct
传递到期望指针的位置。
free(&old)
wouldn't work, as it would provoke undefined behaviour, because the code tried to free memory being allocated on the stack, that is the memory for the pointer variable old
itself. free(&old)
不起作用,因为它会引发未定义的行为,因为代码试图释放分配在堆栈上的内存,也就是指针变量old
本身的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.