c - 在 C 中释放指向链表的双指针

标签 c list pointers

我对 c 有点陌生,尝试使用单个链表来实现堆栈。为了实现 push() 和 pop() 函数,我传递了一个双指针。在 main 中,我将 Node *node_head 初始化为 NULL

我使用 malloc() 和 free() 成功处理内存泄漏,但似乎我在某个地方存在内存泄漏,但我无法弄清楚。释放双指针时我应该采取不同的方法吗?谢谢,这是两个函数:

void stack_push(Node **node_head, int d)
{
    Node *node_new = malloc(sizeof(Node));

    node_new -> data = d;
    node_new -> next = *node_head;
    *node_head = node_new;
}

int stack_pop(Node **node_head)
{
    Node *node_togo = *node_head;
    int d = 0;

    if(node_head)
    {
        d = node_togo -> data;
        *node_head = node_togo -> next;
        free(node_togo);
    }
    return d;
}

最佳答案

代码中唯一的错误是在函数 stack_pop 中。

if(node_head)

当然,你可以检查node_head是否等于NULL,尽管在我看来这是一个 super 检查。但您必须检查 *node_head 是否不等于 NULL。

该函数可能看起来像

int stack_pop(Node **node_head)
{
    int d = 0;

    if( *node_head )
    {
        Node *node_togo = *node_head;

        d = node_togo -> data;

        *node_head = node_togo -> next;

        free( node_togo );

    }

    return d;
}

关于c - 在 C 中释放指向链表的双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26838771/

相关文章:

python - 在 Cython 中使用/编译 C++

c - 通过 'insert bytes' 使 'remove bytes' 和 'insert bytes' 一起工作,并具有正/负偏移量

python - 字典中的关系元组列表

python - 在python中一次迭代列表的两个值

c - 指针和结构的段错误

c - C语言中从字符串中删除一个字符

c - 用 libgit2 实现 'git pull'?

c - 将文件中的内容添加到链表

java - 转换另一个列表中的列表

c - 当给出指向节点的指针时,删除单链表中的节点。分配指针不起作用