c - 将 head 分配给指针 'p' 并在删除 head 后取消分配 'p' 有何意义?

标签 c data-structures linked-list free singly-linked-list

我发现一个函数可以删除链表的头节点并将头移动到下一个节点。如果只需移动 head 即可得到相同的结果,那么将 head 分配给 p,并在移动 head 后取消分配它有什么用呢?

我刚刚使用了 printf("%d", head->data) 和 head = head->next,并得到了相同的结果。我浪费内存了吗?

// Why should I use this :
void deleteFromFront() {
    node p = head;
    printf("\n\tThe deleted element is : %d\n", head->data);
    head = head->next;
    free(p);
}

// And not this :
void deleteFromFront() {
    printf("\n\tThe deleted element is : %d\n", head->data);
    head = head->next;
}

最佳答案

此版本:

node p = head;
printf("\n\tThe deleted element is : %d\n", head->data);
head = head->next;
free(p);

释放旧的头节点,这个版本:

printf("\n\tThe deleted element is : %d\n", head->data);
head = head->next;

没有。如果您想释放旧的头节点,则必须使用第一个版本。如果您释放一 block 内存,则可以在下次调用malloc时重用它。如果您在使用完内存后没有释放内存,您的程序将使用越来越多的内存,因为系统仍然认为您的程序正在使用它。这称为内存泄漏。

关于c - 将 head 分配给指针 'p' 并在删除 head 后取消分配 'p' 有何意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57162939/

相关文章:

c - RPC C 程序中的 fprintf 问题

php - 用 C 代码替换复杂的 PHP 代码

c - 关于正确设置结构指针的简单链表

c++ - 为什么没有发生堆栈溢出?

algorithm - 左子树的深度小于右子树的深度

java - 获取所有重复项

c++ - 为链表重载 operator+

c++ - 链表 C++ 的语法

c++ - linux x64 c++ 为链表分配了太多内存;为什么?

c++ - 如何在 C++ 项目中包含 C/C++ 库(例如 libcurl)(IDE : Eclipse)?