[英]Segmentation fault accessing struct member
I've been learning C and am having problems using linked lists.我一直在学习 C,但在使用链表时遇到了问题。 When looping over a pointer to a linked list I run into segmentation faults and I'm not sure why.
当循环指向链表的指针时,我遇到了分段错误,但我不确定为什么。
Looking at similar questions the suggestion is to allocate the memory, but I find this answer confusing.查看类似问题的建议是分配内存,但我发现这个答案令人困惑。 Do you have to use heap memory for linked lists, and if so why?
链表是否必须使用堆内存,如果是,为什么?
Here is my code:这是我的代码:
#include <stdio.h>
typedef struct Node {
char *name;
struct Node *next;
} Node;
typedef struct Thing {
Node *node;
} Thing;
Thing make_thing()
{
Thing t = {
.node = NULL
};
return t;
}
Thing * add_node(Thing *t, char *name)
{
Node node = {
.name = name,
.next = t->node
};
t->node = &node;
return t;
}
void print_nodes(Thing *t)
{
Node *n = t->node;
while(n != NULL) {
printf("Node: %s\n", n->name);
n = n->next;
}
}
int main()
{
printf("Start\n");
Thing t = make_thing();
add_node(&t, "one");
printf("First %s\n", t.node->name);
print_nodes(&t);
return 0;
}
You are using objects with automatic storage out of their scope:您正在使用自动存储超出其范围的对象:
Node node = {
.name = name,
.next = t->node
};
t->node = &node;
return t;
Here you leak the pointer &node
, which is invalid (out of scope) after the return, to the caller and use it here:在这里,您将返回后无效(超出范围)的指针
&node
泄漏给调用者并在此处使用它:
printf("First %s\n", t.node->name);
You have to allocate memory by using malloc()
for your Node
structure.您必须使用
malloc()
为您的Node
结构分配内存。
Example:例子:
Node *node = malloc(sizeof *node);
node->name = name;
node->next = t->node;
t->node = node;
return t;
You have to care about freeing the memory when it is no longer used to prevent memory leaks.当不再使用内存时,您必须关心释放内存以防止内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.