typedef struct
{
uint32_t field_id;
uint16_t length;
}entry_t;
struct node
{
entry_t *sp_entry;
struct node *next;
}*head;
我有一个名为add()的函数将条目添加到链接列表。将节点添加到链接列表时出现分段错误
void add(entry_t *entry)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->sp_entry = entry;
if (head== NULL)
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
}
请不就是“价值”存储在链表节点本身就是一个指向structure.I我得到一个分段错误在
temp->sp_entry = entry;
这可能是因为我没有为entry_t结构分配内存。我想知道的是这是一个常用的用例吗?如果是,我该怎么做。我必须做什么
temp->sp_entry = malloc(sizeof (entry_t));
在做任务之前?还有更好的方法来实现这一目标吗?
其他信息。
当我运行GDB我得到
p *temp
$3 = {sp_entry = 0x0, next = 0x3e64656269}
的sp_entry看起来是空pointer.This在加的malloc后打印()function.And也是我的代码已经与“-g相结合 - O0-Wall“。一直没有警告
你是否将'head'初始化为NULL?如果没有,你的'struct'定义之后的'head'声明会使'head'未初始化,并且'head == NULL'测试将失败 – pb2q
是的。我将头初始化为NULL。 – liv2hak
尝试在malloc之前删除cast到'struct node *' –