简体   繁体   English

使用带有malloc()和free()的指针的可能的内存泄漏,以及与指针符号的混淆

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM