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;
}
}
请注意,存储在链表节点中的“值”本身就是一个指向结构的指针。我遇到了分段错误
temp->sp_entry = entry;
这可能是因为我没有为 entry_t 结构分配内存。我想知道这是一个常见的用例吗?如果是,我该怎么做。我必须做吗
temp->sp_entry = malloc(sizeof (entry_t));
在做任务之前?还有更优雅的方法来实现这一点吗?
附加信息。
当我运行 gdb 我得到
p *temp
$3 = {sp_entry = 0x0, next = 0x3e64656269}
sp_entry 看起来像是一个空指针。这是在 add() 函数中的 malloc 之后打印的。而且我的代码已与“-g -O0 -Wall”结合使用。没有任何警告