c - (C基础) LinkedList : local elements get deleted after insert method

标签 c linked-list

我需要用 C 写一个 LinkedList, 我在文件中将构造定义为 struct element { int value;结构元素 * 下一个; }; 我还定义了一个 head 元素。 这两个都不是本地的,它们是在整个运行时持续存在的变量。 当我尝试使用 int 值从外部将元素插入 LinkedList 时,我需要围绕此 int 包装一个 element。为此,我创建了一个局部变量 struct element e = { value; 0 };。如果 head 为 null,我将它设为 head,否则我使用 for 循环附加它。

我认为问题是 struct element 类型的局部变量 e 在终止该函数时被删除。因此,如果我将头指向 e,它将继续指向未分配的内存点,因为局部变量 e 不会在函数调用之后持续存在。

提前致谢!

最佳答案

那是因为 struct element e = { value; 0 }; 在堆栈上分配元素。当函数范围终止时,堆栈会自动释放(删除)。寻址事件作用域的堆栈内存是完全有效的,但已终止作用域的寻址是未定义的行为。

您需要通过 malloc(sizeof(struct element)); 在堆上分配它,以使其通过函数范围持久化。

struct element *e = calloc(1, sizeof(struct element));
e->value = value;

return e;

注意:calloc 分配清零内存,malloc 分配未定义内容的内存。

关于c - (C基础) LinkedList : local elements get deleted after insert method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13100303/

相关文章:

c - 在Linux C程序中写入自己的可执行文件,错误 "Text file busy"

php - 链表头节点标识符/指针访问问题

C QueueLinkedList 字符串变量不起作用

c - 释放内存、函数

c - 链表排序不重复

c - 如何在 char 数组中存储 int 数组值?

c - makefile 是否可以自动将所有构建对象移动到 dist 目录?

c - 为什么这是一个非法的常量表达式?

c - 删除链表中的元素,直到找到单词

c - 传递 sprintf 的参数 2 从整数生成指针而不进行强制转换。 C警告